<!DOCTYPE html>


<html lang="zh-CN">
  

    <head>
      <meta charset="utf-8" />
        
      <meta name="description" content="这个人很懒，什么都没留下" />
      
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title> DJ Hong&#39;s BLOG</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/favicon.jpg" />
       
<link rel="stylesheet" href="/dist/main.css">

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css"
      />
      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    <link rel="alternate" href="/atom.xml" title="DJ Hong's BLOG" type="application/atom+xml">
</head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      



<!-- Subtitle -->

<div id="main">
  <section class="outer">
  
  
  <article class="articles">
    
    
    
    
    <article
  id="post-超简单！使用PicGo-Gitee搭建免费图床"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2022/01/19/%E8%B6%85%E7%AE%80%E5%8D%95%EF%BC%81%E4%BD%BF%E7%94%A8PicGo-Gitee%E6%90%AD%E5%BB%BA%E5%85%8D%E8%B4%B9%E5%9B%BE%E5%BA%8A/"
    >超简单！使用PicGo+Gitee搭建免费图床</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/01/19/%E8%B6%85%E7%AE%80%E5%8D%95%EF%BC%81%E4%BD%BF%E7%94%A8PicGo-Gitee%E6%90%AD%E5%BB%BA%E5%85%8D%E8%B4%B9%E5%9B%BE%E5%BA%8A/" class="article-date">
  <time datetime="2022-01-19T14:15:32.000Z" itemprop="datePublished">2022-01-19</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E5%8D%9A%E5%AE%A2/">博客</a>
  </div>
   
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <p>很早就发现以前用的新浪图床，和七牛云图床都相继出现图片图片无法显示的问题，好在提早把图片存在本地，近期抽出点时间解决一下图床的问题。<br>因为我对图床的需求目前仅用于存博客的用图，所以我的唯一需求就是“不要钱”即可！最后发现可以用Gitee来存图，再通过PicGo工具简化传图和复制链接的流程。下面就来介绍一下整体搭建流程：</p>
<h2 id="一、下载安装PicGo，安装Gitee插件"><a href="#一、下载安装PicGo，安装Gitee插件" class="headerlink" title="一、下载安装PicGo，安装Gitee插件"></a>一、下载安装<a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/PicGo/releases">PicGo</a>，安装Gitee插件</h2><p>下载Gitee插件之前，需要确定已安装npm环境。<br><img src="https://gitee.com/hongdongjie/gg266picgo/raw/master/pic4blog/%E5%85%8D%E8%B4%B9%E5%9B%BE%E5%BA%8A/picgo.png"></p>
<h2 id="二、在Gitee创建仓库和私人令牌"><a href="#二、在Gitee创建仓库和私人令牌" class="headerlink" title="二、在Gitee创建仓库和私人令牌"></a>二、在Gitee创建仓库和私人令牌</h2><ol>
<li><p>新建repo时，需要设置为<code>公开的</code>仓库，并勾选<code>初始化仓库</code>。<br><img src="https://gitee.com/hongdongjie/gg266picgo/raw/master/pic4blog/%E5%85%8D%E8%B4%B9%E5%9B%BE%E5%BA%8A/repo.png"></p>
</li>
<li><p>创建好私人令牌，需要及时保存好生成的一串字符，因为它只出现一次。<br><img src="https://gitee.com/hongdongjie/gg266picgo/raw/master/pic4blog/%E5%85%8D%E8%B4%B9%E5%9B%BE%E5%BA%8A/access-token.png"></p>
</li>
</ol>
<h2 id="三、在PicGo中配置Gitee图床参数"><a href="#三、在PicGo中配置Gitee图床参数" class="headerlink" title="三、在PicGo中配置Gitee图床参数"></a>三、在PicGo中配置Gitee图床参数</h2><p>如图配置参数。<code>path</code>表示仓库中具体的文件夹名称，考虑到未来可以将图床用到别的项目上，所以提前先为博客创建专用的文件夹。<br><img src="https://gitee.com/hongdongjie/gg266picgo/raw/master/pic4blog/%E5%85%8D%E8%B4%B9%E5%9B%BE%E5%BA%8A/config.png"></p>
<h2 id="四、使用流程"><a href="#四、使用流程" class="headerlink" title="四、使用流程"></a>四、使用流程</h2><ol>
<li><p>使用时，直接将图片拖动到状态栏的PicGo图标上；PicGo也会读取电脑剪切板上的截图，点开状态栏手动上传即可。<br><img src="https://gitee.com/hongdongjie/gg266picgo/raw/master/pic4blog/%E5%85%8D%E8%B4%B9%E5%9B%BE%E5%BA%8A/upload.png"></p>
</li>
<li><p>上传成功的图片会出现在面板的相册中，点击<code>复制</code>小图标，可以快捷获取Markdown图片代码。<br><img src="https://gitee.com/hongdongjie/gg266picgo/raw/master/pic4blog/%E5%85%8D%E8%B4%B9%E5%9B%BE%E5%BA%8A/album.png"></p>
</li>
</ol>
<h3 id="参考资料："><a href="#参考资料：" class="headerlink" title="参考资料："></a>参考资料：</h3><p><a target="_blank" rel="noopener" href="https://www.jianshu.com/p/f3db16810fea">PicGo+Gitee搭建图床</a></p>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E5%9B%BE%E5%BA%8A/" rel="tag">图床</a></li></ul>

    </footer>
  </div>

    
 
    
</article>

    
    <article
  id="post-职业生涯规划——读《远见》"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2021/08/04/%E8%81%8C%E4%B8%9A%E7%94%9F%E6%B6%AF%E8%A7%84%E5%88%92%E2%80%94%E2%80%94%E8%AF%BB%E3%80%8A%E8%BF%9C%E8%A7%81%E3%80%8B/"
    >职业生涯规划——读《远见》</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2021/08/04/%E8%81%8C%E4%B8%9A%E7%94%9F%E6%B6%AF%E8%A7%84%E5%88%92%E2%80%94%E2%80%94%E8%AF%BB%E3%80%8A%E8%BF%9C%E8%A7%81%E3%80%8B/" class="article-date">
  <time datetime="2021-08-04T02:36:49.000Z" itemprop="datePublished">2021-08-04</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E9%98%85%E8%AF%BB/">阅读</a>
  </div>
   
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <img src="https://gitee.com/hongdongjie/gg266picgo/raw/master/pic4blog/职业生涯规划——读《远见》/封面1.jpg" width = "400" align=center />

<h2 id="引言"><a href="#引言" class="headerlink" title="引言"></a>引言</h2><p>今年而立之年将至，工作也竟有7年之久。这些年，换了几家公司涨了几次薪水，也别无其他成就。作为程序员，到了三十岁，难免都会有中年危机，或遇到职业瓶颈，我也不例外。2020年的一整年，我的状态比较低迷，对未来产生了怀疑和迷茫，但是好在及时调整，制定计划，培养习惯，算是暂时度过了那段时间。但是，对于未来的职业生涯，还未有做过仔细的思考和规划——《远见：如何规划职业生涯3大阶段》这边书在我的书单里吃灰了很长时间，不得不说此时正是阅读这本书的最佳时刻了。</p>
<h2 id="三大职业生涯阶段"><a href="#三大职业生涯阶段" class="headerlink" title="三大职业生涯阶段"></a>三大职业生涯阶段</h2><p>书中列出的3个阶段分别是：</p>
<blockquote>
<p>第一阶段：加添燃料，强势开局<br>第二阶段：锚定甜蜜区，聚焦长板<br>第三阶段：优化长尾，发挥持续影响力</p>
</blockquote>
<p>目前，我国的退休年龄是女性55周岁、男性60周岁，而完成大学本科学业的时间，大概是在22周岁左右。所以，我们的职业生涯总长度平均至少有36年以上的时间（后续计算和陈述），而每个阶段大约为12年。</p>
<h3 id="第一阶段：加添燃料，强势开局"><a href="#第一阶段：加添燃料，强势开局" class="headerlink" title="第一阶段：加添燃料，强势开局"></a>第一阶段：加添燃料，强势开局</h3><p>在第一阶段里，职业生涯对初出茅庐的我们而言充满着未知和挑战。此时正是【蓄力】的好时候，我们需要想方设法去积累未来我们一定会用到的：职业技能、工作经验和人脉关系，这也是作者所描述的职场燃料的3种最基本的形式。</p>
<h4 id="针对职业技能"><a href="#针对职业技能" class="headerlink" title="针对职业技能"></a>针对职业技能</h4><p>“1万小时定律”告诉我们如果想要成为卓越非凡的人，就必须付出坚持不断地努力，这也是任何人从平凡变成世界级大师的必要条件。</p>
<p>不断提升和加强自身的职业技能是最基本的要求，而职业技能不仅指的是解决问题的能力，还需要涉及到：</p>
<ul>
<li>与人沟通的能力</li>
<li>建立自己良好的职业形象的能力</li>
<li>帮助和求助他人的能力</li>
<li>理解和连接他人情绪状态的能力，也就是所谓的EQ</li>
</ul>
<p>这些能力能够帮我们完成大部分的工作，即使从一家公司换到了另一家公司，这些能力依然通用，这也就是作者所描述的“可迁移的技能”。</p>
<h4 id="针对工作经验"><a href="#针对工作经验" class="headerlink" title="针对工作经验"></a>针对工作经验</h4><p>有人会说，工作时间长了，不就有了“丰富”的工作经验了嘛。实际上，大多数人在大多数时间里，都安稳地使用着相同的经验，也就是说，如果我们一直都没有去做一些有挑战性的事情时，我们的工作经验都是和别人重复的没有意义的，对于我们自身而言在职场中是没有竞争力的。</p>
<p>书中提到，如果你非常喜欢当前的工作和环境，但是又不想局限于当前的工作状态或者职位，不凡在完成“本职工作”的情况下，了解更多公司的情况，钻研某个工作中遇到的具体问题，并需要想方设法解决它们，为公司提升效率，带来价值。一个人在公司的价值，恰恰决定了他的职位和薪资。</p>
<p>所以，我们需要“预先”去掌握与职位还不是很匹配的工作经验，才有可能获得我们所渴望的职位。</p>
<h4 id="针对人脉关系"><a href="#针对人脉关系" class="headerlink" title="针对人脉关系"></a>针对人脉关系</h4><blockquote>
<p>“人脉关系可能是最有效、最耐用的一种职场燃料了”</p>
</blockquote>
<p>人脉的重要性对所有人来说，都是不言而喻的。在职场中，我们会遇到许多不同的人：上司、客户、商业伙伴，还有同事，大家相互之间组成的职业生态系统，需要我们持续地去维护。</p>
<h3 id="第二阶段：锚定甜蜜区，聚焦长板"><a href="#第二阶段：锚定甜蜜区，聚焦长板" class="headerlink" title="第二阶段：锚定甜蜜区，聚焦长板"></a>第二阶段：锚定甜蜜区，聚焦长板</h3><p>根据前面的分析，职业生涯的第二阶段大约从踏入职场的12年后开始，此时的我们或许已经小有成就——不错的薪资、身居管理岗位，而如何让自己的职业生涯更近一步呢？作者在这里抛出的观点是：锚定自己喜欢和擅长的工作，这项工作还必须是有市场的，然后只需要将自己的热情和核心长板不断地提升和发扬即可！</p>
<p>在第二阶段中，有的人身居管理或独自创业，身兼管理职能，促使我们迫切地需要提升一些特定的能力，因为我们需要关注更多工作的细节之处，作者在这里提到了“技能冲刺法”，即以90天为一个循环，为提高某一项特定能力而进行周期性密集训练。不断地学习不仅能够完善自身的长板技能，还能增加多角度对工作的认识和思考，综合能力提现差异。</p>
<p>同时，我们需要管理好自己的时间和精力，毕竟在第二阶段，人到中年，良好的睡眠、饮食和锻炼才是能够更好工作和生活的保障。</p>
<h3 id="第三阶段：优化长尾，发挥持续影响力"><a href="#第三阶段：优化长尾，发挥持续影响力" class="headerlink" title="第三阶段：优化长尾，发挥持续影响力"></a>第三阶段：优化长尾，发挥持续影响力</h3><blockquote>
<p>职业生涯后期并不一定就得在压抑中被人遗忘，或在退休的那天遭遇突然打击。合理规划后的第三阶段持续的时间超乎想象，而且回报也相当丰厚，关键就在于主动对这一阶段进行永不懈怠的塑造。</p>
</blockquote>
<p>职业生涯的第三个阶段，不应该是只有等待退休这一条路，在过往的职业生涯所积蓄的职场燃料是我们一生的财富，此时的我们还可以作为工作顾问的形式存在。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>《远见》这本书将职业生涯划分为3个阶段，刷新了我之前对职业生涯的认知，有些人到了30岁的时候，都会觉得自己一事无成，或遇到了职业瓶颈，我觉得可以读读此书，先沉下心分析一下自身情况，并进行职业规划，重新树立目标（甚至野心）。我觉得做事一定要有目标，不然就像一只无头苍蝇，飞到哪儿是哪儿，所做的努力之间毫无关联，劲儿都没往一处使，最后毫无成就也是在所难免的。<br>我每年年初都会为自己定好整年的目标，涵盖了工作、学习和家庭三个方面，前往不要忘记将家庭规划进来，因为要知道，其实我们努力工作的初衷之一不就是为了家庭吗。这里推荐阅读《平衡的智慧》这本书，学习因特尔CTO帕特·基辛格是如何平衡家庭和工作的优先次序的。<br>光定好计划还不够，所以每个月还必须制定OKR，将目标和工作内容细化，并在每个月月底进行总结，已经改进和加强做的不够好的部分。<br>善于使用工具能够帮助我们更好地规划，目前我使用的是OffScreen记录手机的使用情况，以及清单类软件记录工作事项备忘，结合这两个软件我可以知道我每天都做做了什么，玩儿了多久手机，又有多少时间是用手机在工作的。掌握时间分布这一点非常重要，我们必须搞清楚我们每天都在做些什么，有多少时间是花在了没有意义的娱乐上面，当然如果工作时间超出了正常范围也不是一件健康的事情，所以我们规划好自己的职业生涯，掌控时间，好好睡觉，坚持锻炼，劳逸结合，迎接未来的挑战！</p>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E8%AF%BB%E4%B9%A6%E5%BF%83%E5%BE%97/" rel="tag">读书心得</a></li></ul>

    </footer>
  </div>

    
 
    
</article>

    
    <article
  id="post-如何封装一个支持LaTex的Markdown解析器"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2021/02/02/%E5%A6%82%E4%BD%95%E5%B0%81%E8%A3%85%E4%B8%80%E4%B8%AA%E6%94%AF%E6%8C%81LaTex%E7%9A%84Markdown%E8%A7%A3%E6%9E%90%E5%99%A8/"
    >如何封装一个支持LaTex的Markdown解析器</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2021/02/02/%E5%A6%82%E4%BD%95%E5%B0%81%E8%A3%85%E4%B8%80%E4%B8%AA%E6%94%AF%E6%8C%81LaTex%E7%9A%84Markdown%E8%A7%A3%E6%9E%90%E5%99%A8/" class="article-date">
  <time datetime="2021-02-02T11:19:37.000Z" itemprop="datePublished">2021-02-02</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/iOS/">iOS</a>
  </div>
   
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <h2 id="起因"><a href="#起因" class="headerlink" title="起因"></a>起因</h2><p>最近在仿写一款优秀的写作软件，优秀的写作软件支持markdown的解析自然是一个必不可少的功能，在思考如何实现解析器的同时，恰好阅读了钟颖大佬出品的关于<a target="_blank" rel="noopener" href="https://dev.taio.app/#/cn/editor/code-editor">“代码编辑器”</a>的技术文章，发现可以使用 <code>WebView</code>封装 <a target="_blank" rel="noopener" href="https://github.com/markdown-it/markdown-it">markdown-it</a> 和 <a target="_blank" rel="noopener" href="https://highlightjs.org/">highlightjs.org</a>  一类的web项目，低成本地实现一个有着不错效果的CommonMark解析器。</p>
<h2 id="实现过程"><a href="#实现过程" class="headerlink" title="实现过程"></a>实现过程</h2><h3 id="1-HTML文件创建"><a href="#1-HTML文件创建" class="headerlink" title="1. HTML文件创建"></a>1. HTML文件创建</h3><p>创建本地文件 <code>index.html</code>，并输入代码。页面中用到的js文件和资源需要后续创建和生成。<code>&lt;body&gt;</code>标签中唯一的<code>&lt;div&gt;</code>将用于后续插入通过 <code>markdown-it</code>渲染的代码，页面的样式布局通过css文件实现和优化。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no&quot;</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">&quot;stylesheet&quot;</span> <span class="attr">href</span>=<span class="string">&quot;./main.css&quot;</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;./main.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;container&quot;</span> <span class="attr">id</span>=<span class="string">&quot;contents&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="2-JS文件创建"><a href="#2-JS文件创建" class="headerlink" title="2. JS文件创建"></a>2. JS文件创建</h4><p>创建本地文件 <code>index.js</code>，在文件中编写需要注入网页的js代码。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> hljs <span class="keyword">from</span> <span class="string">&#x27;highlight.js&#x27;</span></span><br><span class="line"><span class="keyword">import</span> MarkdownIt <span class="keyword">from</span> <span class="string">&#x27;markdown-it&#x27;</span></span><br><span class="line"><span class="keyword">import</span> emoji <span class="keyword">from</span> <span class="string">&#x27;markdown-it-emoji&#x27;</span></span><br><span class="line"><span class="keyword">import</span> <span class="string">&#x27;./../css/bootstrap.css&#x27;</span></span><br><span class="line"><span class="keyword">import</span> <span class="string">&#x27;./../css/gist.css&#x27;</span></span><br><span class="line"><span class="keyword">import</span> <span class="string">&#x27;./../css/github.css&#x27;</span></span><br><span class="line"><span class="keyword">import</span> <span class="string">&#x27;./../css/index.css&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">window</span>.showMarkdown = <span class="function">(<span class="params">percentEncodedMarkdown, enableImage = <span class="literal">true</span></span>) =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (!percentEncodedMarkdown) &#123;</span><br><span class="line">    <span class="keyword">return</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> markdownText = <span class="built_in">decodeURIComponent</span>(percentEncodedMarkdown)</span><br><span class="line"></span><br><span class="line">  <span class="keyword">let</span> markdown = <span class="keyword">new</span> MarkdownIt(&#123;</span><br><span class="line">    <span class="attr">html</span>: <span class="literal">true</span>,</span><br><span class="line">    <span class="attr">breaks</span>: <span class="literal">true</span>,</span><br><span class="line">    <span class="attr">linkify</span>: <span class="literal">true</span>,</span><br><span class="line">    <span class="attr">highlight</span>: <span class="function"><span class="keyword">function</span>(<span class="params">code</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> hljs.highlightAuto(code).value;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line">  <span class="keyword">if</span> (!enableImage) &#123;</span><br><span class="line">    markdown = markdown.disable(<span class="string">&#x27;image&#x27;</span>)</span><br><span class="line">  &#125;</span><br><span class="line">  markdown.use(emoji)</span><br><span class="line">  markdown.use(<span class="built_in">require</span>(<span class="string">&#x27;markdown-it-latex2img&#x27;</span>))</span><br><span class="line">  <span class="keyword">let</span> html = markdown.render(markdownText)</span><br><span class="line"></span><br><span class="line">  <span class="built_in">document</span>.getElementById(<span class="string">&#x27;contents&#x27;</span>).innerHTML = html</span><br><span class="line">  <span class="keyword">let</span> tables = <span class="built_in">document</span>.querySelectorAll(<span class="string">&#x27;table&#x27;</span>)</span><br><span class="line">  tables.forEach(<span class="function">(<span class="params">table</span>) =&gt;</span> &#123;</span><br><span class="line">    table.classList.add(<span class="string">&#x27;table&#x27;</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">  <span class="keyword">let</span> codes = <span class="built_in">document</span>.querySelectorAll(<span class="string">&#x27;pre code&#x27;</span>)</span><br><span class="line">  codes.forEach(<span class="function">(<span class="params">code</span>) =&gt;</span> &#123;</span><br><span class="line">    hljs.highlightBlock(code)</span><br><span class="line">  &#125;)</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>主要用到的js库有：</p>
<blockquote>
<p><code>markdown-it</code>：100％ CommonMark 语法解析<br><code>highlight.js</code>：代码高亮<br><code>markdown-it-emoji</code>：emoji语法支持<br><code>markdown-it-latex2img</code>：基于服务器端的MathJax解析器</p>
</blockquote>
<p>代码的基本逻辑主要是：<br>1.由于markdown格式的内容被传入时事先进行了编码操作，所以这里需要调用decodeURIComponent()函数对内容先进行解码。<br>2.使用 <code>markdown-it</code>别结合所需插件对内容进行渲染，更多关于 <code>markdown-it</code>的使用和插件支持，可以参考官方的API文档：<a target="_blank" rel="noopener" href="http://markdownit.docschina.org/">《markdown-it 中文文档》</a>。<br>3.将渲染后的代码插入 <code>index.html</code>页面的对应位置，并支持表格（内嵌功能）和代码高亮的显示。</p>
<h3 id="3-控件封装"><a href="#3-控件封装" class="headerlink" title="3. 控件封装"></a>3. 控件封装</h3><p>业务逻辑：创建 <code>WKWebView</code>，并注入js代码（showMarkdown()函数调用）<br>关键<a target="_blank" rel="noopener" href="https://github.com/keitaoouchi/MarkdownView/blob/master/Sources/MarkdownView/MarkdownView.swift">代码</a>：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">@objc</span> <span class="keyword">public</span> <span class="function"><span class="keyword">func</span> <span class="title">load</span>(<span class="params">markdown</span>: <span class="type">String</span>?, <span class="params">enableImage</span>: <span class="type">Bool</span> <span class="operator">=</span> <span class="literal">true</span>)</span> &#123;</span><br><span class="line">  <span class="keyword">guard</span> <span class="keyword">let</span> markdown <span class="operator">=</span> markdown <span class="keyword">else</span> &#123; <span class="keyword">return</span> &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> <span class="keyword">let</span> url <span class="operator">=</span> htmlURL &#123;</span><br><span class="line">    <span class="keyword">let</span> templateRequest <span class="operator">=</span> <span class="type">URLRequest</span>(url: url)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">let</span> escapedMarkdown <span class="operator">=</span> <span class="keyword">self</span>.escape(markdown: markdown) <span class="operator">??</span> <span class="string">&quot;&quot;</span></span><br><span class="line">    <span class="keyword">let</span> imageOption <span class="operator">=</span> enableImage <span class="operator">?</span> <span class="string">&quot;true&quot;</span> : <span class="string">&quot;false&quot;</span></span><br><span class="line">    <span class="keyword">let</span> script <span class="operator">=</span> <span class="string">&quot;window.showMarkdown(&#x27;<span class="subst">\(escapedMarkdown)</span>&#x27;, <span class="subst">\(imageOption)</span>);&quot;</span></span><br><span class="line">    <span class="keyword">let</span> userScript <span class="operator">=</span> <span class="type">WKUserScript</span>(source: script, injectionTime: .atDocumentEnd, forMainFrameOnly: <span class="literal">true</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">let</span> controller <span class="operator">=</span> <span class="type">WKUserContentController</span>()</span><br><span class="line">    controller.addUserScript(userScript)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">let</span> configuration <span class="operator">=</span> <span class="type">WKWebViewConfiguration</span>()</span><br><span class="line">    configuration.userContentController <span class="operator">=</span> controller</span><br><span class="line"></span><br><span class="line">    <span class="keyword">let</span> wv <span class="operator">=</span> <span class="type">WKWebView</span>(frame: <span class="keyword">self</span>.bounds, configuration: configuration)</span><br><span class="line">    wv.scrollView.isScrollEnabled <span class="operator">=</span> <span class="keyword">self</span>.isScrollEnabled</span><br><span class="line">    wv.translatesAutoresizingMaskIntoConstraints <span class="operator">=</span> <span class="literal">false</span></span><br><span class="line">    wv.navigationDelegate <span class="operator">=</span> <span class="keyword">self</span></span><br><span class="line">    addSubview(wv)</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 代码省略：布局约束、空间样式</span></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line"></span><br><span class="line">    wv.load(templateRequest)</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// <span class="doctag">TODO:</span> raise error</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="function"><span class="keyword">func</span> <span class="title">escape</span>(<span class="params">markdown</span>: <span class="type">String</span>)</span> -&gt; <span class="type">String</span>? &#123;</span><br><span class="line">  <span class="keyword">return</span> markdown.addingPercentEncoding(withAllowedCharacters: <span class="type">CharacterSet</span>.alphanumerics)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="4-资源文件打包"><a href="#4-资源文件打包" class="headerlink" title="4. 资源文件打包"></a>4. 资源文件打包</h3><p>到此，代码层面的工作就可以结束了。<br>最后我们需要使用 <code>Webpack</code>工具将js应用程序打包成方便使用的静态资源，输出名为 <code>main.js</code>的文件，将其放置在 <code>index.html</code>文件相同的目录下。这里提供一个可供参考的配置文件：<a target="_blank" rel="noopener" href="https://github.com/keitaoouchi/MarkdownView/blob/master/webassets/webpack.config.js">webpack.config.js</a>。</p>
<h2 id="写在最后"><a href="#写在最后" class="headerlink" title="写在最后"></a>写在最后</h2><p>本文所描述的实现过程，主要参考了三方库 <a target="_blank" rel="noopener" href="https://github.com/keitaoouchi/MarkdownView">MarkdownView</a>，因为需要支持LaTeX的解析，我稍微重写了showMarkdown函数，加入了 <code>markdown-it-latex2img</code>库的使用，能够将数学公式以图片的形式进行展示。过程中，还学习了 <code>Webpack</code>工具的使用和js静态资源的打包。<code>Webview</code>项目的封装能够为原生提供更丰富的功能，能够为复杂的业务实现提供更多的思路和扩展，希望本文能够对需要的人有所帮助。</p>
<h3 id="参考资料："><a href="#参考资料：" class="headerlink" title="参考资料："></a>参考资料：</h3><p><a target="_blank" rel="noopener" href="https://dev.taio.app/#/cn/">Taio开发笔记</a><br><a target="_blank" rel="noopener" href="https://www.runoob.com/w3cnote/webpack-tutorial.html">Webpack教程</a><br><a target="_blank" rel="noopener" href="http://markdown-it.docschina.org/">markdown-it API文档</a><br><a target="_blank" rel="noopener" href="https://github.com/keitaoouchi/MarkdownView">keitaoouchi/MarkdownView</a></p>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/LaTex/" rel="tag">LaTex</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Markdown/" rel="tag">Markdown</a></li></ul>

    </footer>
  </div>

    
 
    
</article>

    
    <article
  id="post-2020年度总结"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2021/01/09/2020%E5%B9%B4%E5%BA%A6%E6%80%BB%E7%BB%93/"
    >2020年度总结</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2021/01/09/2020%E5%B9%B4%E5%BA%A6%E6%80%BB%E7%BB%93/" class="article-date">
  <time datetime="2021-01-09T10:36:52.000Z" itemprop="datePublished">2021-01-09</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/">年终总结</a>
  </div>
   
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <p>2020是个多事之秋，从年初开始的新冠疫情，将大家封锁在家中，而我也在为接下去的一年该如何前行而迷茫着。我试着整理自己的资源，并为2020进行了大方向的规划，准确的说，更像是为2020年写了思维导图式的备忘录。恍然间，时间如白驹过隙，2020终究还是过去了，我希望能够通过总结过去一年的成绩，鼓励做更好的自己，并筹划更好的未来。</p>
<h1 id="工作"><a href="#工作" class="headerlink" title="工作"></a>工作</h1><p>2020加入了一家从事IOT业务的公司，公司的工作节奏是我认为比较舒服的那种，会给够开发人员足够的时间，其中6成的时间用于功能的开发，剩下的时间则是用于测试和修改，这让我们能够有时间对产品进行深入调试和优化，尽可能地保证产品的质量。<br>2020是工作维稳的一年，我离开上一家公司的原因，是因为它的工作内容与我的技术栈和职业规划相悖，过于安稳的状态甚至让技术有所下降。所以，我需要对自己进行调整，让职业规划回归正轨。<br>“物联网+智能家居”是未来势不可挡的趋势，也是我喜欢的行业之一，非常幸运在2020能够找到适合自己，以及自己能够喜欢的工作。<br>同时，作为开发人员，一定要有能够独当一面的作品，所以2020的下半年，“偷偷地”进行着一款写作软件的开发，希望能够在不远的未来，发布这个软件。（给自己挖个坑）</p>
<h1 id="学习"><a href="#学习" class="headerlink" title="学习"></a>学习</h1><p>2020年的年初，虽然对未来有些迷茫，但还是定制了这一年的学习目标（算是一个学习内容备忘录吧）。主要学习内容包括一下几点。</p>
<h2 id="iOS新技术"><a href="#iOS新技术" class="headerlink" title="iOS新技术"></a>iOS新技术</h2><p>在新技术方面，其实有过到底是学习flutter还是swift的彷徨，最终的决定还是继续深入走iOS的技术方向。<br>重新翻出“吃灰”了的<a target="_blank" rel="noopener" href="https://time.geekbang.org/column/intro/161">《戴铭的iOS高手课程》</a>，个人感觉这本书最大的有点就是成列了iOS开发的知识体系，让像我这种遇到瓶颈的开发者能够有清晰的方向去提升。对于文章的内容，其实需要花大量的时间去研究，因为这门课程的内容主要还是对知识体系的介绍，更深入的内容需要开发者从实践、底层等方向去学习的。<br>开发语言方面，着重学习的了Swift语言，除了公司开发必须使用OC之外，不论是自己的独立项目还是LeetCode都使用Swift进行编写。真的。Swift相比OC是用了回不去的语言。</p>
<h2 id="LeetCode算法题"><a href="#LeetCode算法题" class="headerlink" title="LeetCode算法题"></a>LeetCode算法题</h2><p>使用语言：Swift<br>解决问题：</p>
<ul>
<li>简单：95 / 541</li>
<li>中等：18 / 989</li>
<li>困难：01 / 395<br>刷了“大量”的简单问题，进行一个算法的“入门”。太久没有接触算法题了，有些生疏。但是解题还是很有意思的一个事情，每日一题，不多不少，算是每天打卡吧。坚持了两个多月，后期应为工作有些忙碌，稍微有些懈怠了。今年和同事创建了一个LeetCode打卡群，希望大家能够在相互监督的环境下共同成长。同时Swift也在慢慢刷题的过程中，逐渐学习起来了。（哈哈~）</li>
</ul>
<h2 id="源码阅读-博客"><a href="#源码阅读-博客" class="headerlink" title="源码阅读+博客"></a>源码阅读+博客</h2><p>开发人员如何快速提成自己的技术水平呢？其中一个最好的方法就是学习优秀的开发者所设计开发的代码，从中吸取经验并为己所用。从9月份开始，在工作的空闲时间，我会阅读常用的第三方库的源码，并将自己的理解写成博客发布在自己的网站上，所谓“不动笔墨，不读书”吗，有输入也必须有输出，通过写博客的方式，是能够检验自己对内容的理解和巩固的。</p>
<p>以下是源码阅读的链接：</p>
<ul>
<li><a target="_blank" rel="noopener" href="http://blog.gg266.tech/2020/09/03/iOS%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB%E2%80%94%E2%80%94YYModel/">《iOS源码阅读——YYModel》</a></li>
<li><a target="_blank" rel="noopener" href="http://blog.gg266.tech/2020/09/09/iOS%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB%20%E2%80%94%E2%80%94%20MJExtension/"> 《iOS源码阅读 —— MJExtension》</a></li>
<li><a target="_blank" rel="noopener" href="http://blog.gg266.tech/2020/09/14/iOS%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB%20%E2%80%94%E2%80%94%20YYModel%20%20vs%20%20MJExtension/">《iOS源码阅读 —— YYModel vs MJExtension》</a></li>
<li><a target="_blank" rel="noopener" href="http://blog.gg266.tech/2020/11/18/iOS%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB%E2%80%94%E2%80%94MJRefresh/">《iOS源码阅读——MJRefresh》</a></li>
</ul>
<h1 id="阅读"><a href="#阅读" class="headerlink" title="阅读"></a>阅读</h1><p>我们这一代人的时间都是碎片化的，社会节奏太快，就算是在下班时间，也会时不时地接到老板的一通电话，要求就地修改需求。<br>这一年最大的成就可能就是养成了阅读的习惯吧，我给自己设定了每天一小时的阅读打卡任务，要求自己必须完成这项任务。<br>上下班的通勤时间，其实是最好的阅读时间，所以我大部分的阅读时光都是在地铁上度过的，这一年特别幸运的是“遇见”了不少好书，而且也想白岩松老师说的，读书是一件特别神奇的事情，你越去读书，好书就会源源不断地“主动”找到你，然后你就会读到许多优秀的作品。所以读书真的是一件特别幸福的事情。<br>这一年，我的阅读时间总共是122小时，读完了17本书，并在不同的地方留下了自己的足迹。这里推荐微信读书App，非常方便，可以算是一款社交类的阅读软件，而且几乎都是在白嫖🤣不过遇到了好书，我还会购买实体书，以方便后续反复阅读。</p>
<p>以下是读书笔记的链接：</p>
<ul>
<li><a target="_blank" rel="noopener" href="http://blog.gg266.tech/2020/04/03/2020%E5%B9%B43%E6%9C%88%E8%AF%BB%E4%B9%A6%E5%BF%83%E5%BE%97/">《2020年3月读书心得》</a></li>
<li><a target="_blank" rel="noopener" href="http://blog.gg266.tech/2020/04/10/2020%E5%B9%B44%E6%9C%88%E8%AF%BB%E4%B9%A6%E5%BF%83%E5%BE%97/">《2020年4月读书心得》</a></li>
<li><a target="_blank" rel="noopener" href="http://blog.gg266.tech/2020/05/08/2020%E5%B9%B45%E6%9C%88%E8%AF%BB%E4%B9%A6%E5%BF%83%E5%BE%97/">《2020年5月读书心得》</a></li>
<li><a target="_blank" rel="noopener" href="http://blog.gg266.tech/2020/08/31/2020%E5%B9%B48%E6%9C%88%E8%AF%BB%E4%B9%A6%E5%BF%83%E5%BE%97/">《2020年8月读书心得》</a></li>
<li><a target="_blank" rel="noopener" href="http://blog.gg266.tech/2020/09/26/2020%E5%B9%B49%E6%9C%88%E8%AF%BB%E4%B9%A6%E5%BF%83%E5%BE%97/">《2020年9月读书心得》</a></li>
<li><a target="_blank" rel="noopener" href="http://blog.gg266.tech/2020/10/17/2020%E5%B9%B410%E6%9C%88%E8%AF%BB%E4%B9%A6%E5%BF%83%E5%BE%97/">《2020年10月读书心得》</a></li>
</ul>
<h1 id="生活"><a href="#生活" class="headerlink" title="生活"></a>生活</h1><p>对于我自己的生活没有太多可以分享的地方。最重要的是，真的要感谢洪太太，我的老婆大人。为了照顾我们的小宝，你放弃了个人的时间，在一定意义上成为了一名“全职妈妈”。从原来在家人人宠爱的小公主，摇身一变变成了家里的女超人，不过你依旧是，且永远是我心中的小公主。小宝能有现在的成长，也离不开你不停的学习，以及对小宝的认真和耐心的教育。<br>成长真的是一件很神奇的事情，从孩子第一次拿着食物放进自己的嘴里，第一次叫妈妈，第一爬行，第一次独自站立，第一次独自走路，时间真的很快，一晃眼小宝都已经一周岁了，学会了很多技能，也经常会可爱地惹得大家哈哈大笑，当然也有“不乖”的时候，但除了放下已经捏紧的拳头，还能怎么办呢，谁让他那么可爱的。当然，作为父母的职责，是陪伴和帮助孩子，教他明辨是非善恶，未来成为有独立思想的人！我们一直努力着。</p>
<h1 id="展望"><a href="#展望" class="headerlink" title="展望"></a>展望</h1><p>2020有太多可以优化的地方了，在各个方面。<br>工作上，希望能够找到心仪的远程岗位，让“只工作，不上班”的状态早日实现。<br>学习上，继续实行ORK工作法，脚踏实地完成任务，达成目标。<br>阅读上，读书是一个非常好的习惯，我要改变有时候沉迷社交网络的习惯，花费更多的时间投入书籍的怀抱，并影响身边的人，加入阅读的行列。<br>生活上，承担更多照顾和教育孩子义务。相比带孩子，上班真的是太幸福。所以，我想要让我的太太有时间去做自己的事情，或是心中的事业，去实现自己的梦想。</p>
<p>果然啊，又记成了流水账。</p>
<p>总计，2021，继续加油！</p>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E9%9A%8F%E8%AE%B0/" rel="tag">随记</a></li></ul>

    </footer>
  </div>

    
 
    
</article>

    
    <article
  id="post-iOS源码阅读——MJRefresh"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2020/11/18/iOS%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB%E2%80%94%E2%80%94MJRefresh/"
    >iOS源码阅读——MJRefresh</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2020/11/18/iOS%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB%E2%80%94%E2%80%94MJRefresh/" class="article-date">
  <time datetime="2020-11-18T13:14:06.000Z" itemprop="datePublished">2020-11-18</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/iOS/">iOS</a>
  </div>
   
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <p>MJRefresh几乎是我们开发工作中必用的一款三方库，它提供一套非常简单实用的拖拽执行回调事件的解决方案。下面是官方提供的框架图。<br><img src="https://gitee.com/hongdongjie/gg266picgo/raw/master/pic4blog/MJRefresh/MJRefresh.png"><br>其中最常用的几个默认视图类分别是：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">下拉刷新控件：MJRefreshNormalHeader</span><br><span class="line">上拉加载控件：MJRefreshAutoNormalFooter、MJRefreshBackNormalFooter</span><br><span class="line">左滑加载控件：MJRefreshNormalTrailer</span><br></pre></td></tr></table></figure>
<p>下面将对这些类，自上而下地进行分析。</p>
<h2 id="公共基类控件"><a href="#公共基类控件" class="headerlink" title="公共基类控件"></a>公共基类控件</h2><h3 id="MJRefreshComponent"><a href="#MJRefreshComponent" class="headerlink" title="MJRefreshComponent"></a>MJRefreshComponent</h3><p>通过框架图可以看出所有视图都源于同一个基类——<code>MJRefreshComponent</code>，它为子类提供了公用的属性和事件，主要有：</p>
<ul>
<li>回调对象和回调方法</li>
<li>拖拽状态定义和控制</li>
<li>通过KVO，对事件（控件偏移、内容尺寸、手势状态）添加监听（回调响应交给子类实现）</li>
<li>其他：<ul>
<li>拖拽百分比</li>
<li>根据拖拽比例自动切换透明度</li>
</ul>
</li>
</ul>
<p><code>MJRefreshComponent</code>还为子类搭建了基本的逻辑框架：</p>
<h4 id="视图创建"><a href="#视图创建" class="headerlink" title="视图创建"></a>视图创建</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">// 1.初始化</span><br><span class="line">- (instancetype)initWithFrame:(CGRect)frame&#123;;&#125;</span><br><span class="line"></span><br><span class="line">// 2.准备工作</span><br><span class="line">- (void)prepare&#123;;&#125;</span><br><span class="line"></span><br><span class="line">// 3.视图即将被父视图加入</span><br><span class="line">- (void)willMoveToSuperview:(UIView *)newSuperview&#123;</span><br><span class="line">    // 滚动视图初始值的记录</span><br><span class="line">    // 一些值的更新</span><br><span class="line">    // 监听事件的更新</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 4.布局</span><br><span class="line">- (void)layoutSubviews&#123;</span><br><span class="line">    [self placeSubviews];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="滚动视图状态回调"><a href="#滚动视图状态回调" class="headerlink" title="滚动视图状态回调"></a>滚动视图状态回调</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">// 当偏移值发生变化</span><br><span class="line">- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change&#123;&#125;</span><br><span class="line">// 当内容大小发生变化</span><br><span class="line">- (void)scrollViewContentSizeDidChange:(NSDictionary *)change&#123;&#125;</span><br><span class="line">// 当点击手势状态发生变化</span><br><span class="line">- (void)scrollViewPanStateDidChange:(NSDictionary *)change&#123;&#125;</span><br></pre></td></tr></table></figure>

<h3 id="状态设置"><a href="#状态设置" class="headerlink" title="状态设置"></a>状态设置</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">// 状态设置</span><br><span class="line">- (void)setState:(MJRefreshState)state&#123;;&#125;</span><br></pre></td></tr></table></figure>

<h3 id="常用方法"><a href="#常用方法" class="headerlink" title="常用方法"></a>常用方法</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">// 进入刷新状态</span><br><span class="line">- (void)beginRefreshing&#123;;&#125;</span><br><span class="line">// 结束刷新状态</span><br><span class="line">- (void)endRefreshing&#123;;&#125;</span><br></pre></td></tr></table></figure>

<h3 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">// 自动切换透明度</span><br><span class="line">- (void)setAutoChangeAlpha:(BOOL)autoChangeAlpha&#123;;&#125;</span><br><span class="line">- (BOOL)isAutoChangeAlpha&#123;;&#125;</span><br><span class="line">- (void)setAutomaticallyChangeAlpha:(BOOL)automaticallyChangeAlpha&#123;;&#125;</span><br><span class="line"></span><br><span class="line">// 根据拖拽进度实时设置透明度</span><br><span class="line">- (void)setPullingPercent:(CGFloat)pullingPercent&#123;;&#125;</span><br></pre></td></tr></table></figure>

<h2 id="下拉刷新控件（Header）"><a href="#下拉刷新控件（Header）" class="headerlink" title="下拉刷新控件（Header）"></a>下拉刷新控件（Header）</h2><p>下拉刷新控件包含四个类：</p>
<ul>
<li>MJRefreshHeader<ul>
<li>MJRefreshStateHeader<ul>
<li>MJRefreshNormalHeader</li>
</ul>
</li>
<li>MJRefreshGifHeader</li>
</ul>
</li>
</ul>
<h3 id="MJRefreshHeader"><a href="#MJRefreshHeader" class="headerlink" title="MJRefreshHeader"></a>MJRefreshHeader</h3><p><code>MJRefreshHeader</code>类是一个包含了完整的下拉刷新功能逻辑的空白视图，子类<code>MJRefreshStateHeader</code>和<code>MJRefreshGifHeader</code>只需要再添加一些额外的图片和文字，就能提升使用体验和保持代码的简洁易读性。</p>
<h4 id="实现过程"><a href="#实现过程" class="headerlink" title="实现过程"></a>实现过程</h4><h5 id="1-初始化"><a href="#1-初始化" class="headerlink" title="1.初始化"></a>1.初始化</h5><p>创建视图，设置高度和位置。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">- (void)prepare &#123;</span><br><span class="line">    [super prepare];</span><br><span class="line">    // 设置存储key</span><br><span class="line">    // 设置Header的高度</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (void)placeSubviews &#123;</span><br><span class="line">    [super placeSubviews];    </span><br><span class="line">    // 设置Header的位置（y坐标）</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="2-偏移变化：-scrollViewContentSizeDidChange"><a href="#2-偏移变化：-scrollViewContentSizeDidChange" class="headerlink" title="2.偏移变化：- scrollViewContentSizeDidChange"></a>2.偏移变化：<code>- scrollViewContentSizeDidChange</code></h5><p>当用户拖拽滚动控件，是其偏移值发生改变时，会回调<code>- scrollViewContentOffsetDidChange:(NSDictionary *)change</code>方法，在不同的状态下执行对应的逻辑。如果滚动视图已经将Header滚动至屏幕外，则不处理后续逻辑。</p>
<p><code>- scrollViewContentOffsetDidChange:(NSDictionary *)change</code>方法中，有一些关键的变量值，分别是:</p>
<ul>
<li>当前滚动的偏移值：offsetY</li>
<li>头部控件刚好出现的偏移值：happenOffsetY</li>
<li>即将刷新的临界点：normal2pullingOffsetY</li>
</ul>
<p>通过对这些变量值的比较，可以计算出拖拽动作应该被设置为何种状态。</p>
<ul>
<li>控件正在被拖拽<ul>
<li>当拖拽时的偏移量大于临界值，且原状态为闲置时，将状态置为即将刷新</li>
<li>当拖拽时的偏移量小于临界值，且原状态为即将刷新时，将状态重置会闲置</li>
</ul>
</li>
<li>控件未被拖拽，且当前状态为松手进行刷新<ul>
<li>执行开始刷新的方法</li>
</ul>
</li>
<li>控件未被拖拽，且为达到执行刷新回调的临界点</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">if (self.scrollView.isDragging) &#123; // 如果正在拖拽</span><br><span class="line">    self.pullingPercent = pullingPercent;</span><br><span class="line"></span><br><span class="line">    // 当拖拽时的偏移量大于临界值，且原状态为闲置时，将状态置为即将刷新</span><br><span class="line">    if (self.state == MJRefreshStateIdle &amp;&amp; offsetY &lt; normal2pullingOffsetY) &#123;</span><br><span class="line">        // 转为即将刷新状态</span><br><span class="line">        self.state = MJRefreshStatePulling;</span><br><span class="line">    &#125;</span><br><span class="line">    // 当拖拽时的偏移量小于临界值，且原状态为即将刷新时，将状态重置会闲置</span><br><span class="line">    else if (self.state == MJRefreshStatePulling &amp;&amp; offsetY &gt;= normal2pullingOffsetY) &#123;</span><br><span class="line">        // 转为普通状态</span><br><span class="line">        self.state = MJRefreshStateIdle;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">// 原状态为即将刷新，且手已松开</span><br><span class="line">else if (self.state == MJRefreshStatePulling) &#123;</span><br><span class="line">    // 开始刷新</span><br><span class="line">    [self beginRefreshing];</span><br><span class="line">&#125;</span><br><span class="line">// 未达到刷新的偏移量，且手已松开</span><br><span class="line">else if (pullingPercent &lt; 1) &#123;</span><br><span class="line">    // 记录header露出的百分比</span><br><span class="line">    self.pullingPercent = pullingPercent;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里需要注意的是，当Header的状态处于<code>MJRefreshStateRefreshing</code>正在刷新，且控件还在滚动时，会执行<code>- resetInset</code>方法，目的是记录刷新结束后需要调整的上边距值<code>insetTDelta</code>，同时避免 CollectionView 在使用根据 Autolayout 和 内容自动伸缩 Cell, 刷新时导致的 Layout 异常渲染问题。</p>
<h5 id="3-状态设置"><a href="#3-状态设置" class="headerlink" title="3.状态设置"></a>3.状态设置</h5><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">- (void)setState:(MJRefreshState)state&#123;</span><br><span class="line">    _state = state;</span><br><span class="line"></span><br><span class="line">    // 加入主队列的目的是等setState:方法调用完毕、设置完文字后再去布局子控件</span><br><span class="line">    MJRefreshDispatchAsyncOnMainQueue([self setNeedsLayout];)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>视图刷新被加入了异步队列的主线程中，是为了尽量等空间的属性设置完毕后再进行布局的刷新。</p>
<h5 id="4-开始刷新"><a href="#4-开始刷新" class="headerlink" title="4.开始刷新"></a>4.开始刷新</h5><p>执行<code>- beginRefreshing</code>方法，设置状态为<code>MJRefreshStateRefreshing</code>刷新中。<br>方法调用流程如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">1.开始刷新方法调用</span><br><span class="line">- (void)beginRefreshing&#123;</span><br><span class="line">   // ...</span><br><span class="line">   self.state = MJRefreshStateRefreshing;</span><br><span class="line">   // ...</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">2.设置状态为正在刷新中</span><br><span class="line">- (void)setState:(MJRefreshState)state&#123;</span><br><span class="line">    MJRefreshCheckState</span><br><span class="line"></span><br><span class="line">    // 根据状态做事情</span><br><span class="line">    if (state == MJRefreshStateIdle) &#123;</span><br><span class="line">        //...        </span><br><span class="line">    &#125; else if (state == MJRefreshStateRefreshing) &#123;</span><br><span class="line">        [self headerRefreshingAction];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">3.执行刷新动作</span><br><span class="line">- (void)headerRefreshingAction &#123;</span><br><span class="line">    // 主要代码</span><br><span class="line">    [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^&#123;</span><br><span class="line">        if (self.scrollView.panGestureRecognizer.state != UIGestureRecognizerStateCancelled) &#123;</span><br><span class="line">            CGFloat top = self.scrollViewOriginalInset.top + self.mj_h;</span><br><span class="line">            // 增加滚动区域top</span><br><span class="line">            self.scrollView.mj_insetT = top;</span><br><span class="line">            // 设置滚动位置</span><br><span class="line">            CGPoint offset = self.scrollView.contentOffset;</span><br><span class="line">            offset.y = -top;</span><br><span class="line">            [self.scrollView setContentOffset:offset animated:NO];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; completion:^(BOOL finished) &#123;</span><br><span class="line">        [self executeRefreshingCallback];</span><br><span class="line">    &#125;];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>- headerRefreshingAction</code>方法为滚动视图设置了新的<code>inset</code>和<code>offset</code>，使得Header能在滚动视图的顶部停留，用于展示刷新文字动画之类的。</p>
<h5 id="5-结束刷新"><a href="#5-结束刷新" class="headerlink" title="5.结束刷新"></a>5.结束刷新</h5><p>结束刷新需要使用者在耗时操作结束后，主动调用<code>- endRefreshing</code>方法。<br>方法调用流程如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">1.结束刷新方法调用</span><br><span class="line">- (void)endRefreshing&#123;</span><br><span class="line">    MJRefreshDispatchAsyncOnMainQueue(self.state = MJRefreshStateIdle;)</span><br><span class="line">&#125;</span><br><span class="line">2.设置状态为闲置</span><br><span class="line">- (void)setState:(MJRefreshState)state&#123;</span><br><span class="line">    MJRefreshCheckState</span><br><span class="line"></span><br><span class="line">    // 根据状态做事情</span><br><span class="line">    if (state == MJRefreshStateIdle) &#123;</span><br><span class="line">        if (oldState != MJRefreshStateRefreshing) return;</span><br><span class="line"></span><br><span class="line">        [self headerEndingAction];</span><br><span class="line">    &#125; else if (state == MJRefreshStateRefreshing) &#123;</span><br><span class="line">        // ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">3.执行结束动作</span><br><span class="line">- (void)headerEndingAction &#123;;&#125;</span><br></pre></td></tr></table></figure>

<p><code>- headerEndingAction</code>方法将滚动视图的<code>inset</code>重置为刷新状态前的值，将header又隐藏了起来</p>
<h2 id="上拉加载控件（Footer）"><a href="#上拉加载控件（Footer）" class="headerlink" title="上拉加载控件（Footer）"></a>上拉加载控件（Footer）</h2><p>下拉刷新控件包含七个类：</p>
<ul>
<li>MJRefreshFooter<ul>
<li>MJRefreshBackFooter<ul>
<li>MJRefreshBackNormalFooter</li>
<li>MJRefreshBackGifFooter</li>
</ul>
</li>
<li>MJRefreshAutoFooter<ul>
<li>MJRefreshAutoNormalFooter</li>
<li>MJRefreshAutoGifFooter</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="MJRefreshFooter"><a href="#MJRefreshFooter" class="headerlink" title="MJRefreshFooter"></a>MJRefreshFooter</h3><p><code>MJRefreshFooter</code>类不能直接被使用，它仅定义了少量的基础属性和方法，例如构造方法、初始化控件高度，以及无数据加载情况下的处理。</p>
<p>能够直接使用的上拉加载控件是，由<code>MJRefreshFooter</code>衍生出的两个子类，<code>MJRefreshBackFooter</code>和<code>MJRefreshAutoFooter</code>，这两个控件的不同之处在于：</p>
<ul>
<li><code>MJRefreshBackFooter</code>：隐藏在滚动视图的底部边界之外，当拖动至Footer的刷新临界点并放开手，才会执行加载操作。</li>
<li><code>MJRefreshAutoFooter</code>：会紧贴在滚动视图contentSize的边界，如果contentSize的尺寸小于滚动视图的尺寸，用户在不需要滚动的情况下也能看到Footer控件的。它的刷新时机是，用户在拖拽中且达到了Footer刷新临界点。</li>
</ul>
<h3 id="MJRefreshBackFooter"><a href="#MJRefreshBackFooter" class="headerlink" title="MJRefreshBackFooter"></a>MJRefreshBackFooter</h3><h4 id="实现过程-1"><a href="#实现过程-1" class="headerlink" title="实现过程"></a>实现过程</h4><h5 id="1-初始化-1"><a href="#1-初始化-1" class="headerlink" title="1.初始化"></a>1.初始化</h5><p>当MJRefreshBackFooter即将被加入父视图时，会走 <code>- willMoveToSuperview:</code> 方法，并在方法体内调用 <code>- scrollViewContentSizeDidChange:</code>  方法。该方法获取了父视图高度和父视图内容的高度，取二者中较大的数，作为Footer的纵坐标值，确保Footer的位置正好隐藏在视图或内容的最底部。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">- (void)scrollViewContentSizeDidChange:(NSDictionary *)change</span><br><span class="line">&#123;</span><br><span class="line">    [super scrollViewContentSizeDidChange:change];</span><br><span class="line"></span><br><span class="line">    // 内容的高度</span><br><span class="line">    CGFloat contentHeight = self.scrollView.mj_contentH + self.ignoredScrollViewContentInsetBottom;</span><br><span class="line">    // 表格的高度</span><br><span class="line">    CGFloat scrollHeight = self.scrollView.mj_h - self.scrollViewOriginalInset.top - self.scrollViewOriginalInset.bottom + self.ignoredScrollViewContentInsetBottom;</span><br><span class="line">    // 设置位置和尺寸</span><br><span class="line">    self.mj_y = MAX(contentHeight, scrollHeight);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="2-偏移变化：-scrollViewContentSizeDidChange-1"><a href="#2-偏移变化：-scrollViewContentSizeDidChange-1" class="headerlink" title="2.偏移变化：- scrollViewContentSizeDidChange"></a>2.偏移变化：<code>- scrollViewContentSizeDidChange</code></h5><p>当用户在滑动控件使offset发生变化时，会触发 <code>MJRefreshKeyPathContentOffset</code> 的监听事件 —— <code>- scrollViewContentOffsetDidChange</code>。<br><code>MJRefreshBackFooter</code>在<code>- scrollViewContentOffsetDidChange</code>方法里的代码逻辑与<code>MJRefreshHeader</code>是几乎相同的，这里不赘述。需要提一点的是，<code>MJRefreshBackFooter</code>视图的临界值计算需要考虑内容的高度与滚动视图之间的高度差问题。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">#pragma mark 获得scrollView的内容 超出 view 的高度</span><br><span class="line">- (CGFloat)heightForContentBreakView</span><br><span class="line">&#123;</span><br><span class="line">    CGFloat h = self.scrollView.frame.size.height - self.scrollViewOriginalInset.bottom - self.scrollViewOriginalInset.top;</span><br><span class="line">    return self.scrollView.contentSize.height - h;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#pragma mark 刚好看到上拉刷新控件时的contentOffset.y</span><br><span class="line">- (CGFloat)happenOffsetY</span><br><span class="line">&#123;</span><br><span class="line">    CGFloat deltaH = [self heightForContentBreakView];</span><br><span class="line">    // 内容和视图的高度差</span><br><span class="line">    if (deltaH &gt; 0) &#123;</span><br><span class="line">        //  内容高度 &gt; 视图高度</span><br><span class="line">        return deltaH - self.scrollViewOriginalInset.top;</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        // 内容高度 &lt; 视图高度</span><br><span class="line">        return - self.scrollViewOriginalInset.top;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="3-状态设置-1"><a href="#3-状态设置-1" class="headerlink" title="3.状态设置"></a>3.状态设置</h5><p><code>MJRefreshBackFooter</code>类的<code>- setState</code>方法的主要工作就是在开始刷新和结束刷新的时候，为滚动视图更新对应的<code>offset</code>和<code>inset</code>值。</p>
<h3 id="MJRefreshAutoFooter"><a href="#MJRefreshAutoFooter" class="headerlink" title="MJRefreshAutoFooter"></a>MJRefreshAutoFooter</h3><h4 id="实现过程-2"><a href="#实现过程-2" class="headerlink" title="实现过程"></a>实现过程</h4><h5 id="1-初始化-2"><a href="#1-初始化-2" class="headerlink" title="1.初始化"></a>1.初始化</h5><p>当MJRefreshAutoFooter即将被加入父视图时，会调用<code>- willMoveToSuperview:</code> 方法，该方法获取了父视图的内容，作为Footer的纵坐标y的值，确保Footer的位置正好紧贴内容的底部。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">- (void)willMoveToSuperview:(UIView *)newSuperview</span><br><span class="line">&#123;</span><br><span class="line">    [super willMoveToSuperview:newSuperview];</span><br><span class="line"></span><br><span class="line">    if (newSuperview) &#123; // 新的父控件</span><br><span class="line">        if (self.hidden == NO) &#123;</span><br><span class="line">            self.scrollView.mj_insetB += self.mj_h;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        // 设置位置</span><br><span class="line">        self.mj_y = _scrollView.mj_contentH;</span><br><span class="line">    &#125; else &#123; // 被移除了</span><br><span class="line">        if (self.hidden == NO) &#123;</span><br><span class="line">            self.scrollView.mj_insetB -= self.mj_h;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="2-刷新逻辑"><a href="#2-刷新逻辑" class="headerlink" title="2.刷新逻辑"></a>2.刷新逻辑</h5><p><code>MJRefreshAutoFooter</code>控件的位置是紧贴内容的，所以会存在两种情况：<br>1.当<strong>内容高度 &lt; 控件高度</strong>，可以直接看到紧贴内容底部的Footer。这种情况下，加载的时机是在用户松手后调用的。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">- (void)scrollViewPanStateDidChange:(NSDictionary *)change</span><br><span class="line">&#123;</span><br><span class="line">    [super scrollViewPanStateDidChange:change];</span><br><span class="line"></span><br><span class="line">    if (self.state != MJRefreshStateIdle) return;</span><br><span class="line"></span><br><span class="line">    UIGestureRecognizerState panState = _scrollView.panGestureRecognizer.state;</span><br><span class="line"></span><br><span class="line">    switch (panState) &#123;</span><br><span class="line">        // 手松开</span><br><span class="line">        case UIGestureRecognizerStateEnded: &#123;</span><br><span class="line">            if (_scrollView.mj_insetT + _scrollView.mj_contentH &lt;= _scrollView.mj_h) &#123;</span><br><span class="line">                // 内容 &lt; 控件高度</span><br><span class="line">                if (_scrollView.mj_offsetY &gt;= - _scrollView.mj_insetT) &#123; // 向上拽</span><br><span class="line">                    self.triggerByDrag = YES;</span><br><span class="line">                    [self beginRefreshing];</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; else &#123;</span><br><span class="line">                // 内容 &gt; 控件高度</span><br><span class="line">                if (_scrollView.mj_offsetY &gt;= _scrollView.mj_contentH + _scrollView.mj_insetB - _scrollView.mj_h) &#123;</span><br><span class="line">                    self.triggerByDrag = YES;</span><br><span class="line">                    [self beginRefreshing];</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">            break;</span><br><span class="line"></span><br><span class="line">        case UIGestureRecognizerStateBegan: &#123;</span><br><span class="line">            [self resetTriggerTimes];</span><br><span class="line">        &#125;</span><br><span class="line">            break;</span><br><span class="line"></span><br><span class="line">        default:</span><br><span class="line">            break;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>2.当<strong>内容高度 ≥ 控件高度</strong>，需要拖动视图到Footer的加载临界值，但此时不需要松开手，只要滚动视图的偏移量突破了临界值，就会触发加载方法。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change</span><br><span class="line">&#123;</span><br><span class="line">    [super scrollViewContentOffsetDidChange:change];</span><br><span class="line"></span><br><span class="line">    if (self.state != MJRefreshStateIdle || !self.automaticallyRefresh || self.mj_y == 0) return;</span><br><span class="line"></span><br><span class="line">    // 当autoTriggerTimes被设置成-1（滚动时无限加载）</span><br><span class="line">    // 该方法保证拖动放手后，视图还在滚动的情况下，一直保持加载状态</span><br><span class="line"></span><br><span class="line">    // 内容超出控件高度</span><br><span class="line">    if (_scrollView.mj_insetT + _scrollView.mj_contentH &gt; _scrollView.mj_h) &#123;</span><br><span class="line"></span><br><span class="line">        //  内容高度 - 控件高度 + 控件底部边距 + footer高度 * 百分比 - footer高度</span><br><span class="line">        //  内容高度 - 控件高度 + 控件底部边距</span><br><span class="line">        if (_scrollView.mj_offsetY &gt;= _scrollView.mj_contentH - _scrollView.mj_h + self.mj_h * self.triggerAutomaticallyRefreshPercent + _scrollView.mj_insetB - self.mj_h) &#123;</span><br><span class="line">            // 防止手松开时连续调用</span><br><span class="line">            CGPoint old = [change[@&quot;old&quot;] CGPointValue];</span><br><span class="line">            CGPoint new = [change[@&quot;new&quot;] CGPointValue];</span><br><span class="line">            if (new.y &lt;= old.y) return;</span><br><span class="line"></span><br><span class="line">            if (_scrollView.isDragging) &#123;</span><br><span class="line">                self.triggerByDrag = YES;</span><br><span class="line">            &#125;</span><br><span class="line">            // 当底部刷新控件完全出现时，才刷新</span><br><span class="line">            [self beginRefreshing];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>从代码中可以看出，满足刷新的条件是：<br><code>拖动偏移量 ≥ 内容高度 - 控件高度 + 控件底部边距 + footer高度 * 刷新控件露出百分比 - footer高度</code><br>当刷新控件露出百分比为默认值1.时，不等式可以简化为：<br><code>拖动偏移量 ≥ 内容高度 - 控件高度 + 控件底部边距</code></p>
<h5 id="3-无限触发"><a href="#3-无限触发" class="headerlink" title="3.无限触发"></a>3.无限触发</h5><p><code>MJRefreshAutoFooter</code>的另一特点就是无限触发，开发者可以设置属性自定义自动刷新的次数。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">/** 自动触发次数, 默认为 1, 仅在拖拽 ScrollView 时才生效,</span><br><span class="line"></span><br><span class="line"> 如果为 -1, 则为无限触发</span><br><span class="line"> */</span><br><span class="line">@property (nonatomic) NSInteger autoTriggerTimes;</span><br></pre></td></tr></table></figure>
<p>当滚动视图在持续地滚动时（内容高度≥控件高度），会不停地调用<code>-scrollViewContentOffsetDidChange:</code>方法，满足加载条件时从而不停的调用<code>-beginRefreshing</code>方法。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">- (void)beginRefreshing&#123;</span><br><span class="line">    // 新的拖拽动作 &amp;&amp; 剩余触发次数 &amp;&amp; 是否无限触发</span><br><span class="line">    if (self.triggerByDrag &amp;&amp; self.leftTriggerTimes &lt;= 0 &amp;&amp; !self.unlimitedTrigger) &#123;</span><br><span class="line">        return;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    [super beginRefreshing];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当前如果支持无限触发<code>autoTriggerTimes == -1</code>，那么在滚动视图停止滚动前，视图到达加载临界点时都会触发加载任务。</p>
<h5 id="4-状态设置"><a href="#4-状态设置" class="headerlink" title="4.状态设置"></a>4.状态设置</h5><p><code>-beginRefreshing</code>在触发的时候，会将<code>state</code>设置成<code>MJRefreshStateRefreshing</code>，并执行加载数据的回调。<br>通常我们会在加载数据结束的回调方法中去调用<code>-endRefreshing</code>或<code>-endRefreshingWithNoMoreData</code>方法，此时<code>state</code>会被设置成<code>MJRefreshStateIdle</code>或<code>MJRefreshStateNoMoreData</code>，对应<code>-setState:</code>方法中的代码，我们可以看到无限触发次数是在此处进行了控制。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">- (void)setState:(MJRefreshState)state&#123;</span><br><span class="line">    MJRefreshCheckState</span><br><span class="line"></span><br><span class="line">    if (state == MJRefreshStateRefreshing) &#123;</span><br><span class="line">        // 执行加载数据回调</span><br><span class="line">        [self executeRefreshingCallback];</span><br><span class="line">    &#125; else if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) &#123;</span><br><span class="line">        if (self.triggerByDrag) &#123;</span><br><span class="line">            if (!self.unlimitedTrigger) &#123;</span><br><span class="line">                self.leftTriggerTimes -= 1;</span><br><span class="line">            &#125;</span><br><span class="line">            self.triggerByDrag = NO;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        /** 结束刷新 */</span><br><span class="line">        if (MJRefreshStateRefreshing == oldState) &#123;</span><br><span class="line"></span><br><span class="line">            // 当视图开启了分页显示，设置动画和回调</span><br><span class="line">            if (self.scrollView.pagingEnabled) &#123;</span><br><span class="line">                CGPoint offset = self.scrollView.contentOffset;</span><br><span class="line">                offset.y -= self.scrollView.mj_insetB;</span><br><span class="line">                [UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^&#123;</span><br><span class="line">                    self.scrollView.contentOffset = offset;</span><br><span class="line"></span><br><span class="line">                    if (self.endRefreshingAnimationBeginAction) &#123;</span><br><span class="line">                        self.endRefreshingAnimationBeginAction();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125; completion:^(BOOL finished) &#123;</span><br><span class="line">                    if (self.endRefreshingCompletionBlock) &#123;</span><br><span class="line">                        self.endRefreshingCompletionBlock();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;];</span><br><span class="line"></span><br><span class="line">                return;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            // 结束刷新回调</span><br><span class="line">            if (self.endRefreshingCompletionBlock) &#123;</span><br><span class="line">                self.endRefreshingCompletionBlock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="左滑加载控件（Trailer）"><a href="#左滑加载控件（Trailer）" class="headerlink" title="左滑加载控件（Trailer）"></a>左滑加载控件（Trailer）</h2><p><code>MJRefreshTrailer</code> 在实现逻辑上与 <code>MJRefreshBackFooter</code> 是完全一样的，只不过是将部分参数从垂直方向换成了水平方向。</p>
<h2 id="State、Normal-子类控件"><a href="#State、Normal-子类控件" class="headerlink" title="State、Normal 子类控件"></a>State、Normal 子类控件</h2><p>State类型的控件 的主要特点是添加了不同状态的提示文字和刷新时间的显示。<br>Normal类型的控件 在 State类型控件 的基础上，添加了箭头图标和刷新的动画。</p>
<h2 id="Gif-子类控件"><a href="#Gif-子类控件" class="headerlink" title="Gif 子类控件"></a>Gif 子类控件</h2><p>Gif类型的控件可以在拖拽和刷新时展示精美的动画来提升用户体验。<br>主要的两个方法是：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">- (void)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state</span><br><span class="line">&#123;</span><br><span class="line">    if (images == nil) return;</span><br><span class="line"></span><br><span class="line">    self.stateImages[@(state)] = images;</span><br><span class="line">    self.stateDurations[@(state)] = @(duration);</span><br><span class="line"></span><br><span class="line">    /* 根据图片设置控件的高度 */</span><br><span class="line">    UIImage *image = [images firstObject];</span><br><span class="line">    if (image.size.height &gt; self.mj_h) &#123;</span><br><span class="line">        self.mj_h = image.size.height;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (void)setImages:(NSArray *)images forState:(MJRefreshState)state &#123;</span><br><span class="line">    [self setImages:images duration:images.count * 0.1 forState:state];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>刷新控件会根据图片的高度调整自身高度，同时会在没有自定义动画时长的情况下，根据动画的帧数自动设置完整播放一遍动画的时间。</p>
<h3 id="拖拽动画"><a href="#拖拽动画" class="headerlink" title="拖拽动画"></a>拖拽动画</h3><p>开发者可以通过拖拽百分比设置用户在拖拽时的动画，具体实现方式是通过计算当前拖拽的百分比在整体动画中对应的某个帧的图片来获取大致的下标。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">// 通过拖拽百分比设置 Idle~Pulling状态之间的 对应的动画帧</span><br><span class="line">- (void)setPullingPercent:(CGFloat)pullingPercent</span><br><span class="line">&#123;</span><br><span class="line">    [super setPullingPercent:pullingPercent];</span><br><span class="line">    NSArray *images = self.stateImages[@(MJRefreshStateIdle)];</span><br><span class="line">    if (self.state != MJRefreshStateIdle || images.count == 0) return;</span><br><span class="line">    // 停止动画</span><br><span class="line">    [self.gifView stopAnimating];</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    // 设置当前需要显示的图片</span><br><span class="line">    NSUInteger index =  images.count * pullingPercent;</span><br><span class="line">    if (index &gt;= images.count) index = images.count - 1;</span><br><span class="line">    self.gifView.image = images[index];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="刷新动画"><a href="#刷新动画" class="headerlink" title="刷新动画"></a>刷新动画</h3><p>刷新动画会在视图状态处于“即将开始刷新”和“刷新中”进行，使用UIImageView的<code>startAnimating</code>对提前设置好的图片组逐帧播放，默认情况下是无限循环播放的。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">- (void)setState:(MJRefreshState)state</span><br><span class="line">&#123;</span><br><span class="line">    MJRefreshCheckState</span><br><span class="line"></span><br><span class="line">    // 根据状态做事情</span><br><span class="line">    if (state == MJRefreshStatePulling || state == MJRefreshStateRefreshing) &#123;</span><br><span class="line">        // 即将刷新 和 刷新中 状态的动画</span><br><span class="line">        NSArray *images = self.stateImages[@(state)];</span><br><span class="line">        if (images.count == 0) return;</span><br><span class="line"></span><br><span class="line">        [self.gifView stopAnimating];</span><br><span class="line">        if (images.count == 1) &#123; // 单张图片</span><br><span class="line">            self.gifView.image = [images lastObject];</span><br><span class="line">        &#125; else &#123; // 多张图片</span><br><span class="line">            self.gifView.animationImages = images;</span><br><span class="line">            self.gifView.animationDuration = [self.stateDurations[@(state)] doubleValue];</span><br><span class="line">            [self.gifView startAnimating];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; else if (state == MJRefreshStateIdle) &#123;</span><br><span class="line">        // 限制状态停止动画</span><br><span class="line">        [self.gifView stopAnimating];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>MJRefresh清晰整齐的架构为开发者提供了及其丰富的扩展性，而在通常没有定制需求的情况下，默认的控件已经十分够用了。</p>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/MJExtension/" rel="tag">MJExtension</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB/" rel="tag">源码阅读</a></li></ul>

    </footer>
  </div>

    
 
    
</article>

    
    <article
  id="post-2020年10月读书心得"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2020/10/17/2020%E5%B9%B410%E6%9C%88%E8%AF%BB%E4%B9%A6%E5%BF%83%E5%BE%97/"
    >2020年10月读书心得</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2020/10/17/2020%E5%B9%B410%E6%9C%88%E8%AF%BB%E4%B9%A6%E5%BF%83%E5%BE%97/" class="article-date">
  <time datetime="2020-10-17T13:38:08.000Z" itemprop="datePublished">2020-10-17</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E9%98%85%E8%AF%BB/">阅读</a>
  </div>
   
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <img src="https://gitee.com/hongdongjie/gg266picgo/raw/master/pic4blog/2020年10月读书心得/封面1.jpg" width = "400" align=center />

<p>这本书主要描述了马斯克的几段创业史，即早期的从事企业信息上网的Zip2和支付系统PayPal，还有历尽重重困难现在终于成功的太空运输公司SpaceX和纯电动车公司Tesla。书中最有意思的部分就是马斯克在创业时遇到的痛苦和磨难，和他如何去解决这些问题的过程。他从不吝啬将挣到的钱又再次地投入到他梦想的事业中去，同时为此疯狂地工作，并要求其他人像自己一样努力工作，甚至放弃和亲友的相聚时光。成功是需要代价的，但我不认为牺牲和家人的时间是必须的。但是，马斯克那种工作劲头和面对任何困难都毫不放弃的决心，只为实现一个疯狂的梦想是值得人学习的。<br>SpaceX公司创立于2002年，2008年获得NASA的正式合同，直到2012年花了10年十年终于成功地为国际空间站输送货物。这十年内，SpaceX无数次濒临破产，航空业的每一次实验成本都是一个天文数字，更何况是在SpaceX完成火箭回收技术之前，并且它还是一家私营的公司。2020年5月31日，SpaceX将两名宇航员成功送入国际空间站并回收火箭，标志着其成为了第一家实现载人航天的商业公司！<br>而几乎是相同的时间，马斯克还管理运营着Tesla电动汽车公司，而不管造火箭还是造车，马斯克都毫不妥协，他不相信供应商的工作效率和积极性，所以核心零件都由公司自主研发制造，掌握关键技术，并有效控制成本。Tesla还“颠覆”了传统汽车销售模式，采用直销的方式，除了希望带给消费者实惠以外，还有实实在在的服务和便利。这些都是Tesla的企业愿景，具体如何，Tesla车主们应该更有发言权。但从目前的市场情况来讲，将Tesla比作类似于苹果的消费电子类产品，已经一点也不为过了。<br>站在相对于本书的未来角度，看着SpaceX和Tesla历经磨难一步步地走到今天，确实还是挺心潮澎湃的。</p>
<hr>
<img src="https://gitee.com/hongdongjie/gg266picgo/raw/master/pic4blog/2020年10月读书心得/封面2.jpg" width = "400" align=center />

<p>中国历史上第一个实现大一统的秦国，仅仅建立14年，就被推翻，后由汉高祖刘邦称帝建立新朝——西汉。<br>西汉的发展可以说是在对的时间出现了对的人，文、景、武、宣四个皇帝，都是在最合适的时机登场，并取得了影响后世的历史成就。西汉极盛时，疆域东并朝鲜、南据交趾、西逾葱岭、北抵大漠，国富民强，在疆域、政治、军事、经济、文化、民族和外交上皆有建树。只可惜汉宣帝之后，从汉元帝开始的皇帝，一蟹不如一蟹，最终使汉朝一步步走向衰退。<br>《盛世：西汉》这本是引用了详实的史料（多出于《史记》）对西汉盛世进行描写，且不说作者自身观点如何，但从对历史的描述来说，阅读此书给我的感觉用两个字描述足以——过瘾，非常值得一读。</p>
<hr>
<img src="https://gitee.com/hongdongjie/gg266picgo/raw/master/pic4blog/2020年10月读书心得/封面3.jpg" width = "400" align=center />

<p>《能力陷阱》这本书主要讲的是如何提升自己的领导力，而我在阅读次书的时候，将其视为如何提升自己的“外在”能力。所谓的外在能力，我的理解是那些，我们并不擅长的，亦或是我们还不知道的一些能力。与其对应的，当然就是所谓的“内在能力”，内在能力指的是，我们已经掌握的、擅长做的事情的能力。能力陷阱的体现之处就在于，我们都喜欢做那些我们擅长的事，它会让我们非常有成就感，越有这种感觉，我们就越乐意做这件事，使得我们就越擅长做这件事，注意到了吗，这是一个“可怕”的循环。如果没有及时意识到这点，就会被这个“陷阱”套住，而限制了其他能力的发展。有时候，我们总是在做我们“想做”的事情，而忽略了“应该”做的事情。而“应该”做的事情，可能是我们能力外的，这样我们便损失了可以锻炼提升“外在”能力的机会。</p>
<p>有些人可能会说，做自己“喜欢”的事情，是忠于真实的自己。但大家都忽略了一个非常重要的问题：每个人都有多面性，都有多个“自己”。而你要忠于的是哪一个自己？</p>
<p>我认为如此地“忠于自己”，是一种安于舒适圈的借口。</p>
<h4 id="人的一生都在不停地改变"><a href="#人的一生都在不停地改变" class="headerlink" title="人的一生都在不停地改变"></a>人的一生都在不停地改变</h4><blockquote>
<p>心理学家丹尼尔·赖文森（Daniel Levinson）提出了著名的“七年之痒”（Seven-year Itch）的概念。他的研究发现改变可能会循环发生，“稳定”与“改变”两个时期总是不断地在生活里交替发生。</p>
</blockquote>
<p>“稳定”期通常能维持的时间是7年，当然这并不是说7年内不会有任何改变（我们总是在不断地变化），这里的稳定是相对的。这段时期内，我们的任务就是完成各项“计划”。</p>
<p>但一段时间以后，我们会发现有些事并不像我们所计划的那样发展。或许是因为环境变了，而我们的能力却还没有跟上环境的变化，此时便会萌发出一种情绪——焦虑。</p>
<p>“焦虑”的情绪会驱使着我们去“改变”，“改变”期通常持续的时间是三年，在这个时期内，我们需要重新思考自己所做的事，还要思考做这些是的目的。成年人的世界，充满了各种选择和诱惑，我们需要分辨出做什么事情，对自己更有“意义”。</p>
<p>我个人的心得是，面对不断变化的环境，先不要考虑自己的能力问题（因为能力陷阱），然后去选择自己认为有发展前景的事情，去做实现它“应该”做的事，如果这件事有困难，那么恭喜自己，首先不管结果如何，我们都将收货些什么，以此来提升我们的”外在“能力。</p>
<p>”外在“能力的提升，需要我们去实践和验证，而不是一个人坐在安静的地方连续思考3个小时！</p>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E8%AF%BB%E4%B9%A6%E5%BF%83%E5%BE%97/" rel="tag">读书心得</a></li></ul>

    </footer>
  </div>

    
 
    
</article>

    
    <article
  id="post-2020年9月读书心得"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2020/09/26/2020%E5%B9%B49%E6%9C%88%E8%AF%BB%E4%B9%A6%E5%BF%83%E5%BE%97/"
    >2020年9月读书心得</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2020/09/26/2020%E5%B9%B49%E6%9C%88%E8%AF%BB%E4%B9%A6%E5%BF%83%E5%BE%97/" class="article-date">
  <time datetime="2020-09-26T11:58:23.000Z" itemprop="datePublished">2020-09-26</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E9%98%85%E8%AF%BB/">阅读</a>
  </div>
   
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <img src="https://gitee.com/hongdongjie/gg266picgo/raw/master/pic4blog/2020年9月读书心得/封面1.jpg" width = "400" align=center />

<p>一直以来觉自己读书没有什么章法，每次阅读都是毫无目的的一行一行浏览，这样的阅读方法会让我非常容易走神，并且吃不进书的内容。早些时候，因为听过《樊登读书会》的一些音频，感觉樊登对一本书的内容理解和讲述地还不错，即表达清楚了书的内容，又有自己的见解。以《清单革命》这本书为例，我是先停了樊登读书的音频版本，再去读的这本书，结果是阅读这本书让我感觉非常地枯燥和范围，但是音频版本确实不错，值得一听，也是从那时候起，我自己开始使用清单App对日常的生活工作，进行管理备忘和安排。<br>好像扯远了…<br>读完这本书，让我了解到，樊登在读书的时候，会将自己安置在一个安静的地方，这样的环境可以保证在看书的时候能够全身心地投入。接着在看书之前，设置一个阅读的框架：</p>
<blockquote>
<ul>
<li>这本书的使命是什么？</li>
<li>为了解决什么问题？</li>
<li>为了达成使命，或解决问题，提出哪些假设？</li>
<li>提出解决方案。</li>
<li>如何论证这些假设和方案的有效性？</li>
<li>最后得出了什么结论？</li>
<li>这些结论对我们的意义是什么？</li>
</ul>
</blockquote>
<p>然后，带着这些问题到书里去寻找答案。在读罢一本书之后，樊登的做法是静下心来回忆一遍书里的内容，将核心点梳理和复盘成思维导图，再通过语言组织，在尽肯能保证原意的基础上，用自己的方式进行表述。</p>
<p>能够总结出这样的框架，并拥有极强的专注力，记忆力和表达能力，可能要得益于樊登的辩论经历和刻意练习。</p>
<h4 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h4><p>我一直都希望能够有一个系统的读书方法，而本书对我的帮助在于两点。<br>第一是在读书之前应建立大局观。我会在读完一本我认为颇有收获的书之后，写上一篇读书笔记（心得）。这第二就是再创作，读书笔记就是再创作。在陈述一本书的内容时，通过自己的方式，既要表达出自己的观点和理解，又不能脱离其核心观点和原貌。<br><br/><br/></p>
<hr>
<img src="https://gitee.com/hongdongjie/gg266picgo/raw/master/pic4blog/2020年9月读书心得/封面2.jpg" width = "400" align=center />

<h4 id="起因"><a href="#起因" class="headerlink" title="起因"></a>起因</h4><p>《认知天性》这本书，是在阅读《读懂一本书：樊登读书法》的内容中，偶然发现的，我带着能够获取一些学习方法的心态和目的阅读了这本书，结果是效果还不错，至少不会让我觉得枯燥。</p>
<h4 id="学习是挑战天性的必修课"><a href="#学习是挑战天性的必修课" class="headerlink" title="学习是挑战天性的必修课"></a>学习是挑战天性的必修课</h4><p>本事开篇就抛出了一个人们在学习这件事情上的认知错误，那就是人们总是觉得对知识点的反复阅读能够提升它的记忆，并错误的觉得自己已经掌握了知识点。但是，通过对比实验可以证明，反复阅读记忆对掌握知识点其实没有太大的帮助。<br>而需要通过“考试”（或“测试”）这种检索式的学习方法，从反馈中了解对知识的掌握情况，再进行有针对性的刻意练习，方为行之有效的学习方法。</p>
<h4 id="学习的本质-amp-“后刻意练习”时代"><a href="#学习的本质-amp-“后刻意练习”时代" class="headerlink" title="学习的本质 &amp; “后刻意练习”时代"></a>学习的本质 &amp; “后刻意练习”时代</h4><blockquote>
<p>练习从记忆中检索新知识或新技能是有效的学习工具。</p>
</blockquote>
<p>大脑的检索与反复阅读相比，它是有一定意义的思考方式。反复阅读可以理解成是对知识的输入，它带来的流畅感，会给人掌握的错觉。而检索记忆则是通过不同题目、不同场景去考察对知识的掌握度，是一种输出，是一种对掌握能力的反馈，同时还“强迫性”地带动大脑的运转。当知识检索成为了习惯，就可以成为一种条件反射，大大提高解决问题的效率和正确率。</p>
<blockquote>
<p>有间隔、有内容穿插出现，以及内容多样化，其实就是我们生活的本来面貌。</p>
</blockquote>
<p>但是知识检索这种练习，也很容易进入和反复阅读一样的认知误区，那就是集中练习相同的知识或能力，人们总是觉得熟能生巧，但其实可能只是产生了短期记忆，并且如果遇到稍有不同的问题，可能就没法解决了。所以，作者在文中提倡进行有间隔的、有穿插的、具有多样性的练习。这样练习的目的是因为，我们生活中的问题往往是不经意的、没有顺序的出现，问题它不会像我们学习知识一样，反复地有序地按照我们学习的顺序出现。而穿插练习和多样化练习便是根据这个特点应运而生的学习方法，它能帮助我们更好地学习评估问题的背景，以及辨别问题间的差异，再从我们的知识储备中检索最合适的解决方案。最后通过对结果的反思，找出不足，重点学习，做到对知识掌握的巩固和提升。</p>
<h4 id="知识的“滚雪球”效应"><a href="#知识的“滚雪球”效应" class="headerlink" title="知识的“滚雪球”效应"></a>知识的“滚雪球”效应</h4><blockquote>
<p>学习的的三个步骤：心理学家将学习/记忆过程中的三个阶段分为：编码（获得信息）、存储（将信息维持一段时间）、检索（以后使用信息）。</p>
</blockquote>
<p>学习是一个编码（获取），巩固（存储），检索（运用）的过程。已经掌握的知识会形成一条检索路径，当遇到合适场景的时候，能通过一些关键点，检索到对应的知识点。通过有间隔地，穿插式的学习方法，可以避免反复练习造成的麻痹和错觉，更好地对知识点进行区分，建立心智模型。而通过多样化的方式，对知识进行测试，则是通过不同的现实场景，结合关联关键知识点，锻炼和构建检索路径，使得对知识的掌握和运用更加地灵活。在学习的过程中，我们应该趋向于有难度的练习和自主的学习方式，这有助于强化自己的辨析和归纳能力，并且我们应该不惧犯错，通过有效合理的纠正性反馈，能收获更好的学习效果。</p>
<h4 id="心智模型"><a href="#心智模型" class="headerlink" title="心智模型"></a>心智模型</h4><blockquote>
<p>掌握了生活中方方面面的知识，我们会倾向于把做事的步骤集合在一起来解决各种问题。</p>
</blockquote>
<p>由于直觉式的元认知，人们总是会对自身给出高于实际的评估分数，这种认知甚至衍生到了对周遭的理解上，人们会想方设法用自己熟悉的自认为理性的方式来诠释身边发生的事情。这在很大程度上给我们提供了错误的认知和影响了我们的判断能力。而我们需要做的，应该是有意识地分析和推理，并进行自我控制，建立自己的心智模型（将知识集合成解决问题的步骤），通过实践和测验，去发现学习的漏洞，并把它填补完整。</p>
<h4 id="学习风格"><a href="#学习风格" class="headerlink" title="学习风格"></a>学习风格</h4><blockquote>
<p>分析型智力是我们解决问题的能力，典型的例子就是解答测验中的问题；<br>创新型智力是我们综合并应用现有的知识与技能，应对那些新的特殊情况的能力；<br>实践型智力是我们适应日常生活的能力;</p>
</blockquote>
<p>构建适合自己的学习风格，首先要求我们能掌控学习的主动性，利用动态的测验方法，找到自己对于某种知识和技能的缺失，从而进行改善。同时，我们还需要根据不同的文化和学习场景锻炼和运用不同的智力类型（分析型，实践型，创新型），并通过实践去提取其中的原则，构建心智模型的结构，最终成为可以使自己在实际问题中可以捷足先登的诀窍。</p>
<h4 id="终生学习"><a href="#终生学习" class="headerlink" title="终生学习"></a>终生学习</h4><blockquote>
<p>智商测验一直被用来衡量个人的逻辑与语言潜能。这类测验会规定一个智力商数，代表心理年龄与实际年龄的比率，然后再乘以100得出智商值。</p>
</blockquote>
<p>智力水平（也就是我们常说的“智商”）是一种可以通过努力提高的能力，而我们努力的目标和方向应该是为了学到新的知识或技能。在成长的过程中，优秀的执行力甚至比学习技巧更加重要，我们需要通过刻意练习和反复应用，让知识扎根于我们的潜意识之中。</p>
<h4 id="总结-1"><a href="#总结-1" class="headerlink" title="总结"></a>总结</h4><p>学习和提升一定是一个艰辛、痛苦，且见效慢的过程，永远不要让自己长时间处于舒适的状态中，居安思危，不断挑战自己，才能获得成长。</p>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E8%AF%BB%E4%B9%A6%E5%BF%83%E5%BE%97/" rel="tag">读书心得</a></li></ul>

    </footer>
  </div>

    
 
    
</article>

    
    <article
  id="post-iOS源码阅读 —— YYModel  vs  MJExtension"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2020/09/14/iOS%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB%20%E2%80%94%E2%80%94%20YYModel%20%20vs%20%20MJExtension/"
    >iOS源码阅读 —— YYModel  vs  MJExtension</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2020/09/14/iOS%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB%20%E2%80%94%E2%80%94%20YYModel%20%20vs%20%20MJExtension/" class="article-date">
  <time datetime="2020-09-14T12:13:12.000Z" itemprop="datePublished">2020-09-14</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/iOS/">iOS</a>
  </div>
   
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <p><code>YYModel</code>和<code>MJExtension</code>作为JSON模型转换工具，应该算是国内使用者比较多的第三方框架。相信两款都用过的开发者大有人在，我也是其中之一。既然如此，笔者便相继阅读了这两个库的主要源码，并参考<code>YYModel</code>作者<a target="_blank" rel="noopener" href="https://blog.ibireme.com/">ibireme</a>的<a target="_blank" rel="noopener" href="https://blog.ibireme.com/2015/10/23/ios_model_framework_benchmark/">《iOS JSON 模型转换库评测》</a>一文进行了的评测和展开。本文仅代表个人观点，如有异议，欢迎交流指导。</p>
<h3 id="评测对象"><a href="#评测对象" class="headerlink" title="评测对象"></a>评测对象</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">pod &#x27;YYModel&#x27;, &#x27;~&gt; 1.0.4&#x27;</span><br><span class="line"></span><br><span class="line">pod &#x27;MJExtension&#x27;, &#x27;~&gt; 3.2.2&#x27;</span><br></pre></td></tr></table></figure>
<p>评测用例：<a target="_blank" rel="noopener" href="https://github.com/a334713698/JSONModelTransformReview/tree/master/JSONModelTransformReview/GithubUserModel/user.json">GithubUser</a>、<a target="_blank" rel="noopener" href="https://github.com/a334713698/JSONModelTransformReview/tree/master/JSONModelTransformReview/WeiboModel/weibo.json">WeiboStatus</a><br>评测代码：<a target="_blank" rel="noopener" href="https://github.com/a334713698/JSONModelTransformReview">https://github.com/a334713698/JSONModelTransformReview</a><br>运行环境：iOS 13.5 | iPhone XS Max</p>
<h3 id="性能"><a href="#性能" class="headerlink" title="性能"></a>性能</h3><p>性能评测的方法是两个库执行相同次数的JSON模型转换，对比二者的耗时情况。</p>
<h4 id="用例1：GithubUser"><a href="#用例1：GithubUser" class="headerlink" title="用例1：GithubUser"></a>用例1：GithubUser</h4><p><code>GithubUser</code>的数据主要类型是string，和少量的number，主要测试转换库的基本功能。<br>我们分三遍执行两个转换库的相关方法，每遍执行<u><strong>50000</strong></u>次，统计耗时毫秒数。<br>结果如下：</p>
<table>
<thead>
<tr>
<th>Json 2 Model</th>
<th>第一次</th>
<th>第二次</th>
<th>第三次</th>
<th>遍历次数</th>
</tr>
</thead>
<tbody><tr>
<td>MJExtension</td>
<td>1481.25 ms</td>
<td>1468.86 ms</td>
<td>1452.77 ms</td>
<td>1,550,000</td>
</tr>
<tr>
<td>YYModel</td>
<td>257.29 ms</td>
<td>250.48 ms</td>
<td>250.39 ms</td>
<td>1,400,000</td>
</tr>
</tbody></table>
<table>
<thead>
<tr>
<th>Model 2 Json</th>
<th>第一次</th>
<th>第二次</th>
<th>第三次</th>
<th>遍历次数</th>
</tr>
</thead>
<tbody><tr>
<td>MJExtension</td>
<td>1182.23 ms</td>
<td>1162.47 ms</td>
<td>1173.69 ms</td>
<td>1,550,000</td>
</tr>
<tr>
<td>YYModel</td>
<td>382.40 ms</td>
<td>373.91 ms</td>
<td>379.84 ms</td>
<td>1,300,000</td>
</tr>
</tbody></table>
<h4 id="用例2：WeiboStatus"><a href="#用例2：WeiboStatus" class="headerlink" title="用例2：WeiboStatus"></a>用例2：WeiboStatus</h4><p>微博数据<code>WeiboStatus</code>包含大量的复杂类型，主要测试转换库在复杂数据类型情况下的性能。<br>我们分三遍执行这个方法，每遍执行<u><strong>5000</strong></u>次，统计耗时毫秒数。<br>结果如下：</p>
<table>
<thead>
<tr>
<th>Json 2 Model</th>
<th>第一遍</th>
<th>第二遍</th>
<th>第三遍</th>
<th>遍历次数</th>
</tr>
</thead>
<tbody><tr>
<td>MJExtension</td>
<td>4061.77 ms</td>
<td>4054.89 ms</td>
<td>4057.63 ms</td>
<td>2,290,000</td>
</tr>
<tr>
<td>YYModel</td>
<td>813.44 ms</td>
<td>803.64 ms</td>
<td>806.97 ms</td>
<td>2,285,000</td>
</tr>
</tbody></table>
<table>
<thead>
<tr>
<th>Model 2 Json</th>
<th>第一遍</th>
<th>第二遍</th>
<th>第三遍</th>
<th>遍历次数</th>
</tr>
</thead>
<tbody><tr>
<td>MJExtension</td>
<td>596.46 ms</td>
<td>592.42 ms</td>
<td>589.69 ms</td>
<td>475,000</td>
</tr>
<tr>
<td>YYModel</td>
<td>660.04 ms</td>
<td>626.69 ms</td>
<td>615.30 ms</td>
<td>1,215,000</td>
</tr>
</tbody></table>
<h4 id="性能评测结果"><a href="#性能评测结果" class="headerlink" title="性能评测结果"></a>性能评测结果</h4><ul>
<li>每个用例的第一遍评测，都会比后两遍有稍多的用时，是因为第一遍运行，会首次创建和缓存类的类元信息和属性元信息，后两遍再运行的时候，可以直接使用缓存，减少重复生成类元和属性元造成的开销。</li>
<li>系统方法和容器使用方面：<code>MJExtension</code>主要使用的是Foundation框架的NSArray、NSDictionary，以及KVC的方法进行取值和赋值。<code>YYModel</code>主要使用了CoreFoundation框架的容器和遍历方法，通过<code>objc_msgSend</code>消息发送的方式，调用属性的<code>_setter</code>和<code>_getter</code>进行取值和赋值，部分地方还使用inline和纯C函数。</li>
</ul>
<h3 id="容错"><a href="#容错" class="headerlink" title="容错"></a>容错</h3><p>容错性主要是测试，当JSON和Model之间的数据格式不完全相同时，转换库是如何处理的，是否会产生错误或造成Crash。</p>
<table>
<thead>
<tr>
<th>用例 1</th>
<th>JSON属性是：数值，Model属性是：NSString</th>
</tr>
</thead>
<tbody><tr>
<td>MJExtension</td>
<td>100 -&gt; @”100”</td>
</tr>
<tr>
<td>YYModel</td>
<td>100 -&gt; @”100”</td>
</tr>
</tbody></table>
<table>
<thead>
<tr>
<th>用例 2</th>
<th>JSON属性是：数值字符串，Model属性是数值</th>
</tr>
</thead>
<tbody><tr>
<td>MJExtension</td>
<td>@”100” -&gt; 100</td>
</tr>
<tr>
<td>YYModel</td>
<td>@”100” -&gt; 100</td>
</tr>
</tbody></table>
<table>
<thead>
<tr>
<th>用例 3</th>
<th>JSON属性是时间字符串，Model属性是NSDate</th>
</tr>
</thead>
<tbody><tr>
<td>MJExtension</td>
<td>nil，属性类型与值类型不匹配</td>
</tr>
<tr>
<td>YYModel</td>
<td>支持<a target="_blank" rel="noopener" href="https://baike.baidu.com/item/ISO%208601/3910715">ISO标准时间格式</a>的时间字符串自动转成NSDate</td>
</tr>
</tbody></table>
<table>
<thead>
<tr>
<th>用例 4</th>
<th>JSON属性是字符串，Model属性是NSValue</th>
</tr>
</thead>
<tbody><tr>
<td>MJExtension</td>
<td>nil，属性类型与值类型不匹配</td>
</tr>
<tr>
<td>YYModel</td>
<td>nil，属性类型与值类型不匹配</td>
</tr>
</tbody></table>
<p><code>YYModel</code> 和 <code>MJExtension</code> 都会都属性类型与值类型进行类型检测，避免属性被赋予了错误的类型值，以避免潜在的风险。</p>
<blockquote>
<p>这里需要提一下，ibireme发布的<a target="_blank" rel="noopener" href="https://github.com/ibireme/YYModel/tree/master/Benchmark">转换库评测代码</a>发布于2015-09-18。当时<code>MJExtension</code>的最高版本应该是<a target="_blank" rel="noopener" href="https://github.com/CoderMJLee/MJExtension/releases/tag/2.5.7"><code>2.5.7版本</code></a>，此时的代码中还未添加类型检测的代码。</p>
</blockquote>
<p>对于NSDate类型的JSON数据，如果时间格式满足ISO标准，<code>YYModel</code>支持将ISO标准时间格式的字符串，转换成NSDate类型的值；而<code>MJExtension</code>会因为类型检测不匹配，为模型赋空值（nil）。</p>
<h3 id="功能"><a href="#功能" class="headerlink" title="功能"></a>功能</h3><table>
<thead>
<tr>
<th>功能</th>
<th align="center">MJExtension</th>
<th align="center">YYModel</th>
</tr>
</thead>
<tbody><tr>
<td>属性名转换</td>
<td align="center">✅</td>
<td align="center">✅</td>
</tr>
<tr>
<td>自定义属性值转换</td>
<td align="center">✅</td>
<td align="center">✅</td>
</tr>
<tr>
<td>黑白名单</td>
<td align="center">✅</td>
<td align="center">✅</td>
</tr>
<tr>
<td>Coding</td>
<td align="center">✅</td>
<td align="center">✅</td>
</tr>
<tr>
<td>Copying</td>
<td align="center">-</td>
<td align="center">✅</td>
</tr>
<tr>
<td>hash/equal</td>
<td align="center">-</td>
<td align="center">✅</td>
</tr>
<tr>
<td>CoreData</td>
<td align="center">✅</td>
<td align="center">-</td>
</tr>
</tbody></table>
<h3 id="侵入性"><a href="#侵入性" class="headerlink" title="侵入性"></a>侵入性</h3><p><code>YYModel</code>、<code>MJExtension</code>都采用Category来实现，无侵入，并在方法名之前添加了前缀，与原生方法进行区分。</p>
<h3 id="结论"><a href="#结论" class="headerlink" title="结论"></a>结论</h3><p><code>YYModel</code>、<code>MJExtension</code>从逻辑上来说是相似的，都通过Category无侵入性地实现功能，且都是使用runtime动态地获取、创建和缓存类元、属性元信息，再通过对数据的遍历进行转换。具体功能上都支持自定义属性名映射和自定义属性值转换，以及方便的归档接档的方法。少部分功能，略有差异，可根据需求选取。<br>从方法/函数使用上来说，<code>MJExtension</code>使用的是Foundation框架的方法，而<code>YYModel</code>使用的是相比之下更底层的CoreFoundation框架的函数，再配合使用内联和纯C函数，能够做到比<code>MJExtension</code>更少的资源开销，从而在性能上有显著的优势。</p>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/MJExtension/" rel="tag">MJExtension</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/YYModel/" rel="tag">YYModel</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB/" rel="tag">源码阅读</a></li></ul>

    </footer>
  </div>

    
 
    
</article>

    
    <article
  id="post-iOS源码阅读 —— MJExtension"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2020/09/09/iOS%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB%20%E2%80%94%E2%80%94%20MJExtension/"
    >iOS源码阅读 —— MJExtension</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2020/09/09/iOS%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB%20%E2%80%94%E2%80%94%20MJExtension/" class="article-date">
  <time datetime="2020-09-09T12:28:59.000Z" itemprop="datePublished">2020-09-09</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/iOS/">iOS</a>
  </div>
   
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <p>MJExtension是一款开源的，简单易用的字典与模型转换框架。<br>常用的方法，主要是以下几个：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">// JSON|字典 转 模型</span><br><span class="line">+ (instancetype)mj_objectWithKeyValues:(id)keyValues;</span><br><span class="line"></span><br><span class="line">// 通过 JSON|字典 为 模型赋值</span><br><span class="line">- (instancetype)mj_setKeyValues:(id)keyValues;</span><br><span class="line"></span><br><span class="line">// 模型转JSON</span><br><span class="line">- (NSMutableDictionary *)mj_keyValues;</span><br><span class="line"></span><br><span class="line">// JSON数组转模型数组</span><br><span class="line">+ (NSMutableArray *)mj_objectArrayWithKeyValuesArray:(id)keyValuesArray;</span><br></pre></td></tr></table></figure>

<h1 id="功能"><a href="#功能" class="headerlink" title="功能"></a>功能</h1><h2 id="JSON-字典-转-模型"><a href="#JSON-字典-转-模型" class="headerlink" title="JSON|字典 转 模型"></a>JSON|字典 转 模型</h2><h3 id="mj-objectWithKeyValues"><a href="#mj-objectWithKeyValues" class="headerlink" title="+ mj_objectWithKeyValues:"></a>+ mj_objectWithKeyValues:</h3><p><code>+ mj_objectWithKeyValues:</code> 是框架中最简单的JSON转模型的方法，通过直接调用类方法并传入JSON数据即可快速实现转换。而在<code>+ mj_objectWithKeyValues:</code>方法中，实际是调用了<code>+ mj_objectWithKeyValues: context:</code>方法，参数中如果传了<code>contenxt</code>，最终会返回CoreData模型；如果不传，返回已赋值的模型。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">+ (instancetype)mj_objectWithKeyValues:(id)keyValues context:(NSManagedObjectContext *)context</span><br><span class="line">&#123;</span><br><span class="line">    // 获得JSON对象</span><br><span class="line">    keyValues = [keyValues mj_JSONObject];</span><br><span class="line">    MJExtensionAssertError([keyValues isKindOfClass:[NSDictionary class]], nil, [self class], @&quot;keyValues参数不是一个字典&quot;);</span><br><span class="line"></span><br><span class="line">    // 判断是否传入 &quot;contenxt&quot; 参数</span><br><span class="line">    if ([self isSubclassOfClass:[NSManagedObject class]] &amp;&amp; context) &#123;</span><br><span class="line">        NSString *entityName = [NSStringFromClass(self) componentsSeparatedByString:@&quot;.&quot;].lastObject;</span><br><span class="line">        return [[NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:context] mj_setKeyValues:keyValues context:context];</span><br><span class="line">    &#125;</span><br><span class="line">    return [[[self alloc] init] mj_setKeyValues:keyValues];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在为实例赋值的方法中，由于<code>- mj_setKeyValues:</code>实际的实现是调用<code>- mj_setKeyValues: context:</code>。所以我们直接进入<code>- mj_setKeyValues: context:</code>进行分析。</p>
<p>首先，需要将传入的<code>keyValues</code>处理成可用的JSON对象，并获取当前类的类型，以及黑白名单属性。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">// 获得JSON对象</span><br><span class="line">keyValues = [keyValues mj_JSONObject];</span><br><span class="line">MJExtensionAssertError([keyValues isKindOfClass:[NSDictionary class]], self, [self class], @&quot;keyValues参数不是一个字典&quot;);</span><br><span class="line"></span><br><span class="line">Class clazz = [self class];</span><br><span class="line">NSArray *allowedPropertyNames = [clazz mj_totalAllowedPropertyNames];</span><br><span class="line">NSArray *ignoredPropertyNames = [clazz mj_totalIgnoredPropertyNames];</span><br></pre></td></tr></table></figure>

<p>紧接着，调用类的扩展方法<code>+ mj_enumerateProperties:</code>，获取和遍历类的属性列表，通过block参数进行回调，在回调的代码块中，对每个属性进行注意赋值。</p>
<p><strong>核心代码：</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br></pre></td><td class="code"><pre><span class="line">//通过封装的方法回调一个通过运行时编写的，用于返回属性列表的方法。</span><br><span class="line">[clazz mj_enumerateProperties:^(MJProperty *property, BOOL *stop) &#123;</span><br><span class="line">    @try &#123;</span><br><span class="line">        // 0.检测是否被忽略</span><br><span class="line">        if (allowedPropertyNames.count &amp;&amp; ![allowedPropertyNames containsObject:property.name]) return;</span><br><span class="line">        if ([ignoredPropertyNames containsObject:property.name]) return;</span><br><span class="line"></span><br><span class="line">        // 1.取出属性值</span><br><span class="line">        id value;</span><br><span class="line">        NSArray *propertyKeyses = [property propertyKeysForClass:clazz];</span><br><span class="line">        for (NSArray *propertyKeys in propertyKeyses) &#123;</span><br><span class="line">            value = keyValues;</span><br><span class="line">            for (MJPropertyKey *propertyKey in propertyKeys) &#123;</span><br><span class="line">                value = [propertyKey valueInObject:value];</span><br><span class="line">            &#125;</span><br><span class="line">            if (value) break;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        // 值的过滤</span><br><span class="line">        id newValue = [clazz mj_getNewValueFromObject:self oldValue:value property:property];</span><br><span class="line">        if (newValue != value) &#123; // 有过滤后的新值</span><br><span class="line">            [property setValue:newValue forObject:self];</span><br><span class="line">            return;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        // 如果没有值，就直接返回</span><br><span class="line">        if (!value || value == [NSNull null]) return;</span><br><span class="line"></span><br><span class="line">        // 2.复杂处理</span><br><span class="line">        MJPropertyType *type = property.type; // 数据类型类</span><br><span class="line">        Class propertyClass = type.typeClass; // 对象类型</span><br><span class="line">        Class objectClass = [property objectClassInArrayForClass:[self class]]; // 数组中的模型类型</span><br><span class="line"></span><br><span class="line">        // 不可变 -&gt; 可变处理</span><br><span class="line">        if (propertyClass == [NSMutableArray class] &amp;&amp; [value isKindOfClass:[NSArray class]]) &#123;</span><br><span class="line">            value = [NSMutableArray arrayWithArray:value];</span><br><span class="line">        &#125; else if (propertyClass == [NSMutableDictionary class] &amp;&amp; [value isKindOfClass:[NSDictionary class]]) &#123;</span><br><span class="line">            value = [NSMutableDictionary dictionaryWithDictionary:value];</span><br><span class="line">        &#125; else if (propertyClass == [NSMutableString class] &amp;&amp; [value isKindOfClass:[NSString class]]) &#123;</span><br><span class="line">            value = [NSMutableString stringWithString:value];</span><br><span class="line">        &#125; else if (propertyClass == [NSMutableData class] &amp;&amp; [value isKindOfClass:[NSData class]]) &#123;</span><br><span class="line">            value = [NSMutableData dataWithData:value];</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        if (!type.isFromFoundation &amp;&amp; propertyClass) &#123; // 模型属性</span><br><span class="line">            // 既不是基础类型，也不是NS类型。即：基本数据类型</span><br><span class="line">            value = [propertyClass mj_objectWithKeyValues:value context:context];</span><br><span class="line">        &#125; else if (objectClass) &#123;</span><br><span class="line">            if (objectClass == [NSURL class] &amp;&amp; [value isKindOfClass:[NSArray class]]) &#123;</span><br><span class="line">                // string array -&gt; url array</span><br><span class="line">                NSMutableArray *urlArray = [NSMutableArray array];</span><br><span class="line">                for (NSString *string in value) &#123;</span><br><span class="line">                    if (![string isKindOfClass:[NSString class]]) continue;</span><br><span class="line">                    [urlArray addObject:string.mj_url];</span><br><span class="line">                &#125;</span><br><span class="line">                value = urlArray;</span><br><span class="line">            &#125; else &#123; // 字典数组--&gt;模型数组</span><br><span class="line">                value = [objectClass mj_objectArrayWithKeyValuesArray:value context:context];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; else if (propertyClass == [NSString class]) &#123;</span><br><span class="line">            if ([value isKindOfClass:[NSNumber class]]) &#123;</span><br><span class="line">                // NSNumber -&gt; NSString</span><br><span class="line">                value = [value description];</span><br><span class="line">            &#125; else if ([value isKindOfClass:[NSURL class]]) &#123;</span><br><span class="line">                // NSURL -&gt; NSString</span><br><span class="line">                value = [value absoluteString];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; else if ([value isKindOfClass:[NSString class]]) &#123;</span><br><span class="line">            if (propertyClass == [NSURL class]) &#123;</span><br><span class="line">                // NSString -&gt; NSURL</span><br><span class="line">                // 字符串转码</span><br><span class="line">                value = [value mj_url];</span><br><span class="line">            &#125; else if (type.isNumberType) &#123;</span><br><span class="line">                NSString *oldValue = value;</span><br><span class="line"></span><br><span class="line">                // NSString -&gt; NSDecimalNumber, 使用 DecimalNumber 来转换数字, 避免丢失精度以及溢出</span><br><span class="line">                NSDecimalNumber *decimalValue = [NSDecimalNumber decimalNumberWithString:oldValue</span><br><span class="line">                                                                                  locale:numberLocale];</span><br><span class="line"></span><br><span class="line">                // 检查特殊情况</span><br><span class="line">                if (decimalValue == NSDecimalNumber.notANumber) &#123;</span><br><span class="line">                    value = @(0);</span><br><span class="line">                &#125;else if (propertyClass != [NSDecimalNumber class]) &#123;</span><br><span class="line">                    value = [decimalValue mj_standardValueWithTypeCode:type.code];</span><br><span class="line">                &#125; else &#123;</span><br><span class="line">                    value = decimalValue;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                // 如果是BOOL</span><br><span class="line">                if (type.isBoolType) &#123;</span><br><span class="line">                    // 字符串转BOOL（字符串没有charValue方法）</span><br><span class="line">                    // 系统会调用字符串的charValue转为BOOL类型</span><br><span class="line">                    NSString *lower = [oldValue lowercaseString];</span><br><span class="line">                    if ([lower isEqualToString:@&quot;yes&quot;] || [lower isEqualToString:@&quot;true&quot;]) &#123;</span><br><span class="line">                        value = @YES;</span><br><span class="line">                    &#125; else if ([lower isEqualToString:@&quot;no&quot;] || [lower isEqualToString:@&quot;false&quot;]) &#123;</span><br><span class="line">                        value = @NO;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; else if ([value isKindOfClass:[NSNumber class]] &amp;&amp; propertyClass == [NSDecimalNumber class])&#123;</span><br><span class="line">            // 过滤 NSDecimalNumber类型</span><br><span class="line">            if (![value isKindOfClass:[NSDecimalNumber class]]) &#123;</span><br><span class="line">                value = [NSDecimalNumber decimalNumberWithDecimal:[((NSNumber *)value) decimalValue]];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        // 经过转换后, 最终检查 value 与 property 是否匹配</span><br><span class="line">        if (propertyClass &amp;&amp; ![value isKindOfClass:propertyClass]) &#123;</span><br><span class="line">            value = nil;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        // 3.赋值（KVC）</span><br><span class="line">        [property setValue:value forObject:self];</span><br><span class="line">    &#125; @catch (NSException *exception) &#123;</span><br><span class="line">        MJExtensionBuildError([self class], exception.reason);</span><br><span class="line">        MJExtensionLog(@&quot;%@&quot;, exception);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;];</span><br></pre></td></tr></table></figure>
<p>从代码中，可以直观看出，赋值操作主要分为步骤4个步骤。</p>
<h4 id="0-检测是否被忽略"><a href="#0-检测是否被忽略" class="headerlink" title="0.检测是否被忽略"></a>0.检测是否被忽略</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">// 白名单</span><br><span class="line">if (allowedPropertyNames.count &amp;&amp; ![allowedPropertyNames containsObject:property.name]) return;</span><br><span class="line">// 黑名单</span><br><span class="line">if ([ignoredPropertyNames containsObject:property.name]) return;</span><br></pre></td></tr></table></figure>
<p>判断黑白名单中是否包含相应的属性名称。</p>
<h4 id="1-取出属性值"><a href="#1-取出属性值" class="headerlink" title="1.取出属性值"></a>1.取出属性值</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">id value;</span><br><span class="line">NSArray *propertyKeyses = [property propertyKeysForClass:clazz];</span><br><span class="line">for (NSArray *propertyKeys in propertyKeyses) &#123;</span><br><span class="line">    value = keyValues;</span><br><span class="line">    for (MJPropertyKey *propertyKey in propertyKeys) &#123;</span><br><span class="line">        value = [propertyKey valueInObject:value];</span><br><span class="line">    &#125;</span><br><span class="line">    if (value) break;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 值的过滤</span><br><span class="line">id newValue = [clazz mj_getNewValueFromObject:self oldValue:value property:property];</span><br><span class="line">if (newValue != value) &#123; // 有过滤后的新值</span><br><span class="line">    [property setValue:newValue forObject:self];</span><br><span class="line">    return;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 如果没有值，就直接返回</span><br><span class="line">if (!value || value == [NSNull null]) return;</span><br></pre></td></tr></table></figure>
<p>因为同一个成员属性，父类和子类的行为可能不一致（originKey、propertyKeys、objectClassInArray），所以其键值可能是一个数组，通过循环这个数组尝试获取值。<br>对值得过滤，指的是使用者通过实现<code>- (id)mj_newValueFromOldValue: property:</code>方法，对结果进行进一步的处理（比如字符串日期处理为NSDate、字符串nil处理为@””）。</p>
<h4 id="2-复杂处理"><a href="#2-复杂处理" class="headerlink" title="2.复杂处理"></a>2.复杂处理</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">MJPropertyType *type = property.type; // 数据类型的信息</span><br><span class="line">Class propertyClass = type.typeClass; // 属性的类型</span><br><span class="line">Class objectClass = [property objectClassInArrayForClass:[self class]]; // 数组中模型的类型</span><br><span class="line"></span><br><span class="line">// 不可变 -&gt; 可变处理</span><br><span class="line">if (propertyClass == [NSMutableArray class] &amp;&amp; [value isKindOfClass:[NSArray class]]) &#123;</span><br><span class="line">    value = [NSMutableArray arrayWithArray:value];</span><br><span class="line">&#125; else if (propertyClass == [NSMutableDictionary class] &amp;&amp; [value isKindOfClass:[NSDictionary class]]) &#123;</span><br><span class="line">    value = [NSMutableDictionary dictionaryWithDictionary:value];</span><br><span class="line">&#125; else if (propertyClass == [NSMutableString class] &amp;&amp; [value isKindOfClass:[NSString class]]) &#123;</span><br><span class="line">    value = [NSMutableString stringWithString:value];</span><br><span class="line">&#125; else if (propertyClass == [NSMutableData class] &amp;&amp; [value isKindOfClass:[NSData class]]) &#123;</span><br><span class="line">    value = [NSMutableData dataWithData:value];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">if (!type.isFromFoundation &amp;&amp; propertyClass) &#123; // 模型属性</span><br><span class="line">    // 既不是基础类型，也不是NS类型。即：基本数据类型</span><br><span class="line">    value = [propertyClass mj_objectWithKeyValues:value context:context];</span><br><span class="line">&#125; else if (objectClass) &#123;</span><br><span class="line">    if (objectClass == [NSURL class] &amp;&amp; [value isKindOfClass:[NSArray class]]) &#123;</span><br><span class="line">        // string array -&gt; url array</span><br><span class="line">        NSMutableArray *urlArray = [NSMutableArray array];</span><br><span class="line">        for (NSString *string in value) &#123;</span><br><span class="line">            if (![string isKindOfClass:[NSString class]]) continue;</span><br><span class="line">            [urlArray addObject:string.mj_url];</span><br><span class="line">        &#125;</span><br><span class="line">        value = urlArray;</span><br><span class="line">    &#125; else &#123; // 字典数组--&gt;模型数组</span><br><span class="line">        value = [objectClass mj_objectArrayWithKeyValuesArray:value context:context];</span><br><span class="line">    &#125;</span><br><span class="line">&#125; else if (propertyClass == [NSString class]) &#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125; else if ([value isKindOfClass:[NSString class]]) &#123;</span><br><span class="line"></span><br><span class="line">&#125; else if ([value isKindOfClass:[NSNumber class]] &amp;&amp; propertyClass == [NSDecimalNumber class])&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>复杂处理，主要是对属性值的类型进行判断，属性值的类型只要分为：模型属性（自定义类）、数组属性和其他属性（NS类型）。<br>模型属性的value，需要通过继续调用<code>- mj_objectWithKeyValues:value context:</code>方法，将字典转换成模型。<br>数组属性的值，则需要根据数组中模型的类型，进行循环转换。<br>其他情况的值，可以通过简单的转化或者直接使用。</p>
<h4 id="3-赋值"><a href="#3-赋值" class="headerlink" title="3.赋值"></a>3.赋值</h4><p>至此，属性信息和值都有了。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">// 经过转换后, 最终检查 value 与 property 是否匹配</span><br><span class="line">if (propertyClass &amp;&amp; ![value isKindOfClass:propertyClass]) &#123;</span><br><span class="line">    value = nil;</span><br><span class="line">&#125;</span><br><span class="line">[property setValue:value forObject:self];</span><br></pre></td></tr></table></figure>
<p>在确定 value的值 与 property得类型 确实匹配后，通过KVC进行赋值。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> *  设置成员变量的值</span><br><span class="line"> */</span><br><span class="line">- (void)setValue:(id)value forObject:(id)object</span><br><span class="line">&#123;</span><br><span class="line">    if (self.type.KVCDisabled || value == nil) return;</span><br><span class="line">    [object setValue:value forKey:self.name];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>到此，JSON转模型的工作就完成了。</p>
<h2 id="模型-转-JSON-字典"><a href="#模型-转-JSON-字典" class="headerlink" title="模型 转 JSON|字典"></a>模型 转 JSON|字典</h2><h3 id="mj-keyValues"><a href="#mj-keyValues" class="headerlink" title="- mj_keyValues"></a>- mj_keyValues</h3><p>模型转JSON的方法主要有：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">// 转换并返回模型中所有属性的键值对</span><br><span class="line">- (NSMutableDictionary *)mj_keyValues;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> @para keys 需要返回的特定键的数组</span><br><span class="line"> @return 特定关键词的键值对</span><br><span class="line"> */</span><br><span class="line">- (NSMutableDictionary *)mj_keyValuesWithKeys:(NSArray *)keys;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> @para ignoredKeys 需要忽略的特定键的数组</span><br><span class="line"> @return 除特定关键词的其他有效键值对</span><br><span class="line"> */</span><br><span class="line">- (NSMutableDictionary *)mj_keyValuesWithIgnoredKeys:(NSArray *)ignoredKeys;</span><br></pre></td></tr></table></figure>
<p>以上方法统一调用了<code>- mj_keyValuesWithKeys:ignoredKeys:</code>，让我们直接进入这个方法一探究竟。<br><code>- mj_keyValuesWithKeys:ignoredKeys:</code>方法与JSON转模型的核心逻辑是极其相似的，即通过遍历类的所有属性，进行相关操作，这里我们直接进入代码块，进行分析。</p>
<h4 id="0-检测是否被忽略-1"><a href="#0-检测是否被忽略-1" class="headerlink" title="0.检测是否被忽略"></a>0.检测是否被忽略</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">// 白名单</span><br><span class="line">if (allowedPropertyNames.count &amp;&amp; ![allowedPropertyNames containsObject:property.name]) return;</span><br><span class="line">// 黑名单</span><br><span class="line">if ([ignoredPropertyNames containsObject:property.name]) return;</span><br><span class="line">// 只需要返回的特定键</span><br><span class="line">if (keys.count &amp;&amp; ![keys containsObject:property.name]) return;</span><br><span class="line">// 需要被忽略的特定键</span><br><span class="line">if ([ignoredKeys containsObject:property.name]) return;</span><br></pre></td></tr></table></figure>
<p>返回的结果，不仅可以对黑白名单中的属性进行筛选，还可以根据具体场景设置需要返回和忽略的特定键值。</p>
<h4 id="1-取出属性值-1"><a href="#1-取出属性值-1" class="headerlink" title="1.取出属性值"></a>1.取出属性值</h4><p>使用KVC取值。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">id value = [property valueForObject:self];</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> *  获得成员变量的值</span><br><span class="line"> */</span><br><span class="line">- (id)valueForObject:(id)object</span><br><span class="line">&#123;</span><br><span class="line">    if (self.type.KVCDisabled) return [NSNull null];</span><br><span class="line"></span><br><span class="line">    id value = [object valueForKey:self.name];</span><br><span class="line"></span><br><span class="line">    // 32位BOOL类型转换json后成Int类型</span><br><span class="line">    /** https://github.com/CoderMJLee/MJExtension/issues/545 */</span><br><span class="line">    // 32 bit device OR 32 bit Simulator</span><br><span class="line">#if defined(__arm__) || (TARGET_OS_SIMULATOR &amp;&amp; !__LP64__)</span><br><span class="line">    if (self.type.isBoolType) &#123;</span><br><span class="line">        value = @([(NSNumber *)value boolValue]);</span><br><span class="line">    &#125;</span><br><span class="line">#endif</span><br><span class="line"></span><br><span class="line">    return value;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="2-模型属性和数组的处理"><a href="#2-模型属性和数组的处理" class="headerlink" title="2.模型属性和数组的处理"></a>2.模型属性和数组的处理</h4><p>如果当前的属性属于模型类型或数组，则需要对 <code>value</code> 进行递归调用 <code>- mj_keyValues</code> 方法，直至最终得到非模型和非数组的数据类型。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">MJPropertyType *type = property.type;</span><br><span class="line">Class propertyClass = type.typeClass;</span><br><span class="line">if (!type.isFromFoundation &amp;&amp; propertyClass) &#123;</span><br><span class="line">    value = [value mj_keyValues];</span><br><span class="line">&#125; else if ([value isKindOfClass:[NSArray class]]) &#123;</span><br><span class="line">    // 3.处理数组里面有模型的情况</span><br><span class="line">    value = [NSObject mj_keyValuesArrayWithObjectArray:value];</span><br><span class="line">&#125; else if (propertyClass == [NSURL class]) &#123;</span><br><span class="line">    value = [value absoluteString];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="3-赋值-1"><a href="#3-赋值-1" class="headerlink" title="3.赋值"></a>3.赋值</h4><p>在对结果<code>keyValues</code>进行赋值之前，需要先判断创建键值时，是否引用了替换键 —— 也就是在<code>+ mj_replacedKeyFromPropertyName</code>方法中返回的自定义映射表。<br>对于没有引用替换键的值，可以直接赋值。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">keyValues[property.name] = value;</span><br></pre></td></tr></table></figure>
<p>对于引用了替换键的值，需要获取原始的key，最终结果也将返回最原始的JSON或字典。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line">// 获取原始key</span><br><span class="line">NSArray *propertyKeys = [[property propertyKeysForClass:clazz] firstObject];</span><br><span class="line">NSUInteger keyCount = propertyKeys.count;</span><br><span class="line">// 创建字典</span><br><span class="line">__block id innerContainer = keyValues;</span><br><span class="line">[propertyKeys enumerateObjectsUsingBlock:^(MJPropertyKey *propertyKey, NSUInteger idx, BOOL *stop) &#123;</span><br><span class="line">    // 下一个属性</span><br><span class="line">    MJPropertyKey *nextPropertyKey = nil;</span><br><span class="line">    if (idx != keyCount - 1) &#123;</span><br><span class="line">        nextPropertyKey = propertyKeys[idx + 1];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    if (nextPropertyKey) &#123; // 不是最后一个key</span><br><span class="line">        // 当前propertyKey对应的字典或者数组</span><br><span class="line">        id tempInnerContainer = [propertyKey valueInObject:innerContainer];</span><br><span class="line">        if (tempInnerContainer == nil || [tempInnerContainer isKindOfClass:[NSNull class]]) &#123;</span><br><span class="line">            if (nextPropertyKey.type == MJPropertyKeyTypeDictionary) &#123;</span><br><span class="line">                tempInnerContainer = [NSMutableDictionary dictionary];</span><br><span class="line">            &#125; else &#123;</span><br><span class="line">                tempInnerContainer = [NSMutableArray array];</span><br><span class="line">            &#125;</span><br><span class="line">            if (propertyKey.type == MJPropertyKeyTypeDictionary) &#123;</span><br><span class="line">                innerContainer[propertyKey.name] = tempInnerContainer;</span><br><span class="line">            &#125; else &#123;</span><br><span class="line">                innerContainer[propertyKey.name.intValue] = tempInnerContainer;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        if ([tempInnerContainer isKindOfClass:[NSMutableArray class]]) &#123;</span><br><span class="line">            NSMutableArray *tempInnerContainerArray = tempInnerContainer;</span><br><span class="line">            int index = nextPropertyKey.name.intValue;</span><br><span class="line">            while (tempInnerContainerArray.count &lt; index + 1) &#123;</span><br><span class="line">                [tempInnerContainerArray addObject:[NSNull null]];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        innerContainer = tempInnerContainer;</span><br><span class="line">    &#125; else &#123; // 最后一个key</span><br><span class="line">        if (propertyKey.type == MJPropertyKeyTypeDictionary) &#123;</span><br><span class="line">            innerContainer[propertyKey.name] = value;</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            innerContainer[propertyKey.name.intValue] = value;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;];</span><br></pre></td></tr></table></figure>

<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p><strong>核心代码：</strong></p>
<ul>
<li>JSON|字典转模型的各类方法，最终都会调用<code>- mj_setKeyValues:(id)keyValues context:</code></li>
<li>模型转JSON|字典的各类方法，最终都会调用<code>- (NSMutableDictionary *)mj_keyValuesWithKeys: ignoredKeys:</code></li>
</ul>
<p><strong>性能方面:</strong></p>
<ul>
<li>使用runtime动态生成类的属性信息，并通过缓存机制进行性能提优。</li>
</ul>
<p><strong>容错方面</strong></p>
<ul>
<li>在JSON|字典转模型最后赋值之前，会对值和属性的类型进行一致性的判断。如果不匹配，<code>value</code>会被置为nil，避免潜在的Crash风险。</li>
</ul>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/MJExtension/" rel="tag">MJExtension</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB/" rel="tag">源码阅读</a></li></ul>

    </footer>
  </div>

    
 
    
</article>

    
    <article
  id="post-iOS源码阅读——YYModel"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h2 itemprop="name">
  <a class="article-title" href="/2020/09/03/iOS%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB%E2%80%94%E2%80%94YYModel/"
    >iOS源码阅读——YYModel</a> 
</h2>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2020/09/03/iOS%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB%E2%80%94%E2%80%94YYModel/" class="article-date">
  <time datetime="2020-09-03T15:14:23.000Z" itemprop="datePublished">2020-09-03</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/iOS/">iOS</a>
  </div>
   
    </div>
      
    <div class="article-entry" itemprop="articleBody">
       
  <p>YYModel作为一个 iOS/OSX 模型转换框架，为JSON与数据模型之间的转换，提供了高性能的解决方案。</p>
<p>在我个人的日常开发中，主要使用的方法有以下几个：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">// JSON|字典 转 模型</span><br><span class="line">+ (nullable instancetype)yy_modelWithJSON:(id)json;</span><br><span class="line">+ (nullable instancetype)yy_modelWithDictionary:(NSDictionary *)dictionary;</span><br><span class="line"></span><br><span class="line">// 通过 JSON|字典 为 模型赋值</span><br><span class="line">- (BOOL)yy_modelSetWithJSON:(id)json;</span><br><span class="line">- (BOOL)yy_modelSetWithDictionary:(NSDictionary *)dic;</span><br><span class="line"></span><br><span class="line">// 模型转JSON</span><br><span class="line">- (NSString *)yy_modelToJSONString;</span><br><span class="line"></span><br><span class="line">// JSON数组转模型数组</span><br><span class="line">+ (nullable NSArray *)yy_modelArrayWithClass:(Class)cls json:(id)json;</span><br></pre></td></tr></table></figure>

<p>由于多个功能，最终调用的方法是相同的，所以这里仅列出主要方法的代码解析。</p>
<h1 id="功能"><a href="#功能" class="headerlink" title="功能"></a>功能</h1><h2 id="JSON转模型"><a href="#JSON转模型" class="headerlink" title="JSON转模型"></a>JSON转模型</h2><h3 id="yy-modelWithDictionary"><a href="#yy-modelWithDictionary" class="headerlink" title="+ yy_modelWithDictionary:"></a>+ yy_modelWithDictionary:</h3><p>由于调用<code>+ yy_modelWithJSON:</code>方法时，方法内部先将JSON序列化为可用的字典，然后调用<code>+ yy_modelWithDictionary:</code>方法。所以我们直接进入<code>+ yy_modelWithDictionary:</code>进行分析。</p>
<p><strong>代码：</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> 通过一组 键-值对(NSDictionary)，创建和返回一个新的实例</span><br><span class="line"> 此方法是线程安全的。</span><br><span class="line"></span><br><span class="line"> @参数： dictionary  一组能够映射实例属性的 键-值对(dictionary)</span><br><span class="line"> 无效的键值对将会被忽略。</span><br><span class="line"></span><br><span class="line"> @返回： 一个通过 键-值对(dictionary) 创建的新实例，出错的情况下返回nil。</span><br><span class="line"></span><br><span class="line"> @说明： 字典中的 key 和 value 将分别映射在模型的属性名，和属性值上。</span><br><span class="line"> 如果值得类型不发与属性相匹配，此方法将尝试根据如下规则，进行转化：</span><br><span class="line"></span><br><span class="line">     `NSString` or `NSNumber` -&gt; c number, such as BOOL, int, long, float, NSUInteger...</span><br><span class="line">     `NSString` -&gt; NSDate, parsed with format &quot;yyyy-MM-dd&#x27;T&#x27;HH:mm:ssZ&quot;, &quot;yyyy-MM-dd HH:mm:ss&quot; or &quot;yyyy-MM-dd&quot;.</span><br><span class="line">     `NSString` -&gt; NSURL.</span><br><span class="line">     `NSValue` -&gt; struct or union, such as CGRect, CGSize, ...</span><br><span class="line">     `NSString` -&gt; SEL, Class.</span><br><span class="line"> */</span><br><span class="line"></span><br><span class="line">+ (instancetype)yy_modelWithDictionary:(NSDictionary *)dictionary &#123;</span><br><span class="line">    if (!dictionary || dictionary == (id)kCFNull) return nil;</span><br><span class="line">    if (![dictionary isKindOfClass:[NSDictionary class]]) return nil;</span><br><span class="line"></span><br><span class="line">    // 创建当前类的类对象实例</span><br><span class="line">    Class cls = [self class];</span><br><span class="line">    // 创建和获取 模型的元类（包含类的详细信息）</span><br><span class="line">    _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:cls];</span><br><span class="line"></span><br><span class="line">    // 判断使用者是否自定义 类的（子类）类型</span><br><span class="line">    if (modelMeta-&gt;_hasCustomClassFromDictionary) &#123;</span><br><span class="line">        cls = [cls modelCustomClassForDictionary:dictionary] ?: cls;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    // 创建实例实例</span><br><span class="line">    NSObject *one = [cls new];</span><br><span class="line"></span><br><span class="line">    // 为属性赋值</span><br><span class="line">    if ([one yy_modelSetWithDictionary:dictionary]) return one;</span><br><span class="line">    return nil;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>+ yy_modelWithDictionary:</code>方法中，主要做了三件事：1.确定类型；2.创建实例；3.为实例赋值。</p>
<h4 id="1-确定类型"><a href="#1-确定类型" class="headerlink" title="1. 确定类型"></a>1. 确定类型</h4><p>在类方法中使用<code>[self class]</code>可以轻松获取当前类的类对象，在这里作者通过类对象创建了该类的类元<code>_YYModelMeta *model</code>，类元中包含了丰富的关于该类的信息。</p>
<p><strong><code>_YYModelMeta</code> 类元的定义：</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">/// 模型对象的类元信息</span><br><span class="line">@interface _YYModelMeta : NSObject &#123;</span><br><span class="line">    @package</span><br><span class="line">    YYClassInfo *_classInfo;</span><br><span class="line">    /// Key:mapped key and key path, Value:_YYModelPropertyMeta.  数据结构：&#123;&quot;pic&quot;: [_YYModelPropertyMeta new]&#125;</span><br><span class="line">    NSDictionary *_mapper;</span><br><span class="line">    /// Array&lt;_YYModelPropertyMeta&gt;, 所有有效属性元的数组</span><br><span class="line">    NSArray *_allPropertyMetas;</span><br><span class="line">    /// Array&lt;_YYModelPropertyMeta&gt;, 映射到键值路径的属性元</span><br><span class="line">    NSArray *_keyPathPropertyMetas;</span><br><span class="line">    /// Array&lt;_YYModelPropertyMeta&gt;, 映射到多个键的属性元</span><br><span class="line">    NSArray *_multiKeysPropertyMetas;</span><br><span class="line">    /// 有效的键值对数量，所谓有效即包含 _getter、_setter、成员变量。 值与 _mapper.count 相同</span><br><span class="line">    NSUInteger _keyMappedCount;</span><br><span class="line">    /// 数据类型</span><br><span class="line">    YYEncodingNSType _nsType;</span><br><span class="line"></span><br><span class="line">    BOOL _hasCustomWillTransformFromDictionary;</span><br><span class="line">    BOOL _hasCustomTransformFromDictionary;</span><br><span class="line">    BOOL _hasCustomTransformToDictionary;</span><br><span class="line">    BOOL _hasCustomClassFromDictionary;</span><br><span class="line">&#125;</span><br><span class="line">@end</span><br></pre></td></tr></table></figure>
<p>在确定类型之前，需要先判断使用者是否根据不同情况自定义了返回类的（子类）类型，即是否实现了<code>+ modelCustomClassForDictionary:(NSDictionary *)dictionary;</code>方法返回自定义类型。</p>
<p><strong>官方示例：</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">@class YYCircle, YYRectangle, YYLine;</span><br><span class="line"></span><br><span class="line">@implementation YYShape</span><br><span class="line"></span><br><span class="line">+ (Class)modelCustomClassForDictionary:(NSDictionary*)dictionary &#123;</span><br><span class="line">    if (dictionary[@&quot;radius&quot;] != nil) &#123;</span><br><span class="line">        return [YYCircle class];</span><br><span class="line">    &#125; else if (dictionary[@&quot;width&quot;] != nil) &#123;</span><br><span class="line">        return [YYRectangle class];</span><br><span class="line">    &#125; else if (dictionary[@&quot;y2&quot;] != nil) &#123;</span><br><span class="line">        return [YYLine class];</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        return [self class];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">@end</span><br></pre></td></tr></table></figure>

<h4 id="2-创建实例"><a href="#2-创建实例" class="headerlink" title="2. 创建实例"></a>2. 创建实例</h4><p>确定数据类型后，通过类对象快速创建实例。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">NSObject *one = [cls new];</span><br></pre></td></tr></table></figure>

<h4 id="3-为实例赋值"><a href="#3-为实例赋值" class="headerlink" title="3. 为实例赋值"></a>3. 为实例赋值</h4><p>调用 <code>-yy_modelSetWithDictionary:</code> 方法为实例赋值。</p>
<p><strong>代码：</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br></pre></td><td class="code"><pre><span class="line">- (BOOL)yy_modelSetWithDictionary:(NSDictionary *)dic &#123;</span><br><span class="line">    if (!dic || dic == (id)kCFNull) return NO;</span><br><span class="line">    if (![dic isKindOfClass:[NSDictionary class]]) return NO;</span><br><span class="line"></span><br><span class="line">    // 创建和获取 模型的元类（包含类的详细信息）</span><br><span class="line">    _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:object_getClass(self)];</span><br><span class="line"></span><br><span class="line">    // 判断当前类的有效属性数量</span><br><span class="line">    if (modelMeta-&gt;_keyMappedCount == 0) return NO;</span><br><span class="line"></span><br><span class="line">    // 判断使用者是否自定义了转换映射</span><br><span class="line">    if (modelMeta-&gt;_hasCustomWillTransformFromDictionary) &#123;</span><br><span class="line">        dic = [((id&lt;YYModel&gt;)self) modelCustomWillTransformFromDictionary:dic];</span><br><span class="line">        if (![dic isKindOfClass:[NSDictionary class]]) return NO;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    // 创建 模型设置上下文</span><br><span class="line">    ModelSetContext context = &#123;0&#125;;</span><br><span class="line">    context.modelMeta = (__bridge void *)(modelMeta);</span><br><span class="line">    context.model = (__bridge void *)(self);</span><br><span class="line">    context.dictionary = (__bridge void *)(dic); //dic or json</span><br><span class="line"></span><br><span class="line">    //  比较 元模型的键值数量 &amp; 传入字典的键值数量</span><br><span class="line">    if (modelMeta-&gt;_keyMappedCount &gt;= CFDictionaryGetCount((CFDictionaryRef)dic)) &#123;</span><br><span class="line">        /**</span><br><span class="line">         @function CFDictionaryApplyFunction</span><br><span class="line">         对字典中的每个键值对调用函数一次。</span><br><span class="line"></span><br><span class="line">         @param  theDict</span><br><span class="line">         要查的字典。</span><br><span class="line"></span><br><span class="line">         @param  applier</span><br><span class="line">         要对字典中的每个值调用一次的回调函数。</span><br><span class="line"></span><br><span class="line">         @param context</span><br><span class="line">         一个指针大小的用户定义值，作为第三个参数传递给applier函数，但此函数不使用它。</span><br><span class="line"></span><br><span class="line">         */</span><br><span class="line">        CFDictionaryApplyFunction((CFDictionaryRef)dic, ModelSetWithDictionaryFunction, &amp;context);</span><br><span class="line"></span><br><span class="line">        if (modelMeta-&gt;_keyPathPropertyMetas) &#123;</span><br><span class="line">            CFArrayApplyFunction((CFArrayRef)modelMeta-&gt;_keyPathPropertyMetas,</span><br><span class="line">                                 CFRangeMake(0, CFArrayGetCount((CFArrayRef)modelMeta-&gt;_keyPathPropertyMetas)),</span><br><span class="line">                                 ModelSetWithPropertyMetaArrayFunction,</span><br><span class="line">                                 &amp;context);</span><br><span class="line">        &#125;</span><br><span class="line">        if (modelMeta-&gt;_multiKeysPropertyMetas) &#123;</span><br><span class="line">            CFArrayApplyFunction((CFArrayRef)modelMeta-&gt;_multiKeysPropertyMetas,</span><br><span class="line">                                 CFRangeMake(0, CFArrayGetCount((CFArrayRef)modelMeta-&gt;_multiKeysPropertyMetas)),</span><br><span class="line">                                 ModelSetWithPropertyMetaArrayFunction,</span><br><span class="line">                                 &amp;context);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        /**</span><br><span class="line">         @function CFArrayApplyFunction</span><br><span class="line">         对数组中的每个元素调用函数一次。</span><br><span class="line"></span><br><span class="line">         @param theArray</span><br><span class="line">         要操作的数组。</span><br><span class="line"></span><br><span class="line">         @param range</span><br><span class="line">         要将函数应用于的数组中的值范围。</span><br><span class="line"></span><br><span class="line">         @param applier</span><br><span class="line">         对数组中给定范围内的每个值调用一次的回调函数。如果此参数不是指向正确原型的函数的指针，则行为未定义。如果在应用程序函数期望的范围内存在或不能正确应用的值，则该行为是未定义的。</span><br><span class="line"></span><br><span class="line">         @param context</span><br><span class="line">         一个指针大小的用户定义值，它作为第二个参数传递给applier函数，但此函数不使用它。如果上下文不是applier函数所期望的内容，则行为是未定义的。</span><br><span class="line"></span><br><span class="line">         */</span><br><span class="line">        CFArrayApplyFunction((CFArrayRef)modelMeta-&gt;_allPropertyMetas,</span><br><span class="line">                             CFRangeMake(0, modelMeta-&gt;_keyMappedCount),</span><br><span class="line">                             ModelSetWithPropertyMetaArrayFunction,</span><br><span class="line">                             &amp;context);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    if (modelMeta-&gt;_hasCustomTransformFromDictionary) &#123;</span><br><span class="line">        return [((id&lt;YYModel&gt;)self) modelCustomTransformFromDictionary:dic];</span><br><span class="line">    &#125;</span><br><span class="line">    return YES;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里会先判断使用者是否对数据字典做了额外的处理，即是否实现了 <code>-modelCustomWillTransformFromDictionary:</code> 方法。如果有，则返回和使用自定义的字典。</p>
<p>一切准备就绪，创建模型设置上下文<code>ModelSetContext context</code>，准备赋值。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">typedef struct &#123;</span><br><span class="line">    void *modelMeta;  ///&lt; _YYModelMeta 类元</span><br><span class="line">    void *model;      ///&lt; id (self) 实例本身</span><br><span class="line">    void *dictionary; ///&lt; NSDictionary (json) 数据字典（json）</span><br><span class="line">&#125; ModelSetContext;</span><br></pre></td></tr></table></figure>
<p>比较 <code>类元的有效键值数量</code> 和 <code>传入字典的键值数量</code>，以较小的代价进行属性的遍历赋值（减少不必要的循环次数）。这里分别使用<code>CFDictionaryApplyFunction( )</code>和<code>CFArrayApplyFunction( )</code> 对应 <code>ModelSetWithDictionaryFunction( )</code>和<code>ModelSetWithPropertyMetaArrayFunction( )</code>，进行遍历调用。二者最终都是通过 <code>ModelSetValueForProperty( )</code> 函数进行赋值的。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">static void ModelSetValueForProperty(__unsafe_unretained id model,// 实例对象</span><br><span class="line">                                     __unsafe_unretained id value,// 值</span><br><span class="line">                                     __unsafe_unretained _YYModelPropertyMeta *meta //属性元</span><br><span class="line">                                     )</span><br></pre></td></tr></table></figure>

<p><code>ModelSetValueForProperty( )</code> 函数中对属性的数据进行了详细的类型判断，主要分为三大类（C的基础数据类型、Foundation的NS数据类型、自定义数据类型）。除了C的基本数据类型，后者都通过消息发送 <code>objc_msgSend</code> 的方式，调用属性的 <code>meta-&gt;_setter</code> 方法进行赋值。</p>
<p>由于实现代码较长，这里就不展示了，有兴趣的可以自行查看源码：<a target="_blank" rel="noopener" href="https://github.com/ibireme/YYModel/blob/master/YYModel/NSObject+YYModel.m">《YYModel/NSObject+YYModel.m》第784~1098行</a>。</p>
<p>到此，JSON转模型的工作就完成了。</p>
<h2 id="模型转JSON"><a href="#模型转JSON" class="headerlink" title="模型转JSON"></a>模型转JSON</h2><h3 id="yy-modelToJSONString"><a href="#yy-modelToJSONString" class="headerlink" title="+ yy_modelToJSONString:"></a>+ yy_modelToJSONString:</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">- (id)yy_modelToJSONObject &#123;</span><br><span class="line">    /*</span><br><span class="line">     Apple said:</span><br><span class="line">     The top level object is an NSArray or NSDictionary.</span><br><span class="line">     All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.</span><br><span class="line">     All dictionary keys are instances of NSString.</span><br><span class="line">     Numbers are not NaN or infinity.</span><br><span class="line">     */</span><br><span class="line">    id jsonObject = ModelToJSONObjectRecursive(self);</span><br><span class="line">    if ([jsonObject isKindOfClass:[NSArray class]]) return jsonObject;</span><br><span class="line">    if ([jsonObject isKindOfClass:[NSDictionary class]]) return jsonObject;</span><br><span class="line">    return nil;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (NSData *)yy_modelToJSONData &#123;</span><br><span class="line">    id jsonObject = [self yy_modelToJSONObject];</span><br><span class="line">    if (!jsonObject) return nil;</span><br><span class="line">    return [NSJSONSerialization dataWithJSONObject:jsonObject options:0 error:NULL];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (NSString *)yy_modelToJSONString &#123;</span><br><span class="line">    NSData *jsonData = [self yy_modelToJSONData];</span><br><span class="line">    if (jsonData.length == 0) return nil;</span><br><span class="line">    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>从方法实现中不难看出，模型转JSON主要依赖于递归函数 <code>ModelToJSONObjectRecursive</code>，该函数最终将返回一个有效的JSON对象（NSArray/NSDictionary/NSString/NSNumber/NSNull）。</p>
<p><strong><code>ModelToJSONObjectRecursive</code> 内部实现代码拆解：</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">if (!model || model == (id)kCFNull) return model;</span><br><span class="line">if ([model isKindOfClass:[NSString class]]) return model;</span><br><span class="line">if ([model isKindOfClass:[NSNumber class]]) return model;</span><br><span class="line">if ([model isKindOfClass:[NSURL class]]) return ((NSURL *)model).absoluteString;</span><br><span class="line">if ([model isKindOfClass:[NSAttributedString class]]) return ((NSAttributedString *)model).string;</span><br><span class="line">if ([model isKindOfClass:[NSDate class]]) return [YYISODateFormatter( ) stringFromDate:(id)model];</span><br><span class="line">if ([model isKindOfClass:[NSData class]]) return nil;</span><br></pre></td></tr></table></figure>
<p>当模型值符合或接近目标类型时，可做简单的转换或直接返回.</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line">// 字典</span><br><span class="line">if ([model isKindOfClass:[NSDictionary class]]) &#123;</span><br><span class="line">    if ([NSJSONSerialization isValidJSONObject:model]) return model;</span><br><span class="line">    NSMutableDictionary *newDic = [NSMutableDictionary new];</span><br><span class="line">    [((NSDictionary *)model) enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) &#123;</span><br><span class="line">        NSString *stringKey = [key isKindOfClass:[NSString class]] ? key : key.description;</span><br><span class="line">        if (!stringKey) return;</span><br><span class="line">        id jsonObj = ModelToJSONObjectRecursive(obj);</span><br><span class="line">        if (!jsonObj) jsonObj = (id)kCFNull;</span><br><span class="line">        newDic[stringKey] = jsonObj;</span><br><span class="line">    &#125;];</span><br><span class="line">    return newDic;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 集合</span><br><span class="line">if ([model isKindOfClass:[NSSet class]]) &#123;</span><br><span class="line">    NSArray *array = ((NSSet *)model).allObjects;</span><br><span class="line">    if ([NSJSONSerialization isValidJSONObject:array]) return array;</span><br><span class="line">    NSMutableArray *newArray = [NSMutableArray new];</span><br><span class="line">    for (id obj in array) &#123;</span><br><span class="line">        if ([obj isKindOfClass:[NSString class]] || [obj isKindOfClass:[NSNumber class]]) &#123;</span><br><span class="line">            [newArray addObject:obj];</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            id jsonObj = ModelToJSONObjectRecursive(obj);</span><br><span class="line">            if (jsonObj &amp;&amp; jsonObj != (id)kCFNull) [newArray addObject:jsonObj];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    return newArray;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 数组</span><br><span class="line">if ([model isKindOfClass:[NSArray class]]) &#123;</span><br><span class="line">    if ([NSJSONSerialization isValidJSONObject:model]) return model;</span><br><span class="line">    NSMutableArray *newArray = [NSMutableArray new];</span><br><span class="line">    for (id obj in (NSArray *)model) &#123;</span><br><span class="line">        if ([obj isKindOfClass:[NSString class]] || [obj isKindOfClass:[NSNumber class]]) &#123;</span><br><span class="line">            [newArray addObject:obj];</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            id jsonObj = ModelToJSONObjectRecursive(obj);</span><br><span class="line">            if (jsonObj &amp;&amp; jsonObj != (id)kCFNull) [newArray addObject:jsonObj];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    return newArray;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当模型值为字典、集合数组类型时，需要遍历和递归其内部元素，直至逐一转化成有效的JSON对象。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line">// 自定义类</span><br><span class="line">_YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:[model class]];</span><br><span class="line">if (!modelMeta || modelMeta-&gt;_keyMappedCount == 0) return nil;</span><br><span class="line">NSMutableDictionary *result = [[NSMutableDictionary alloc] initWithCapacity:64];</span><br><span class="line">__unsafe_unretained NSMutableDictionary *dic = result; // avoid retain and release in block</span><br><span class="line">[modelMeta-&gt;_mapper enumerateKeysAndObjectsUsingBlock:^(NSString *propertyMappedKey, _YYModelPropertyMeta *propertyMeta, BOOL *stop) &#123;</span><br><span class="line">    if (!propertyMeta-&gt;_getter) return;</span><br><span class="line"></span><br><span class="line">    id value = nil;</span><br><span class="line">    if (propertyMeta-&gt;_isCNumber) &#123;</span><br><span class="line">        value = ModelCreateNumberFromProperty(model, propertyMeta);</span><br><span class="line">    &#125; else if (propertyMeta-&gt;_nsType) &#123;</span><br><span class="line">        id v = ((id (*)(id, SEL))(void *) objc_msgSend)((id)model, propertyMeta-&gt;_getter);</span><br><span class="line">        value = ModelToJSONObjectRecursive(v);</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        switch (propertyMeta-&gt;_type &amp; YYEncodingTypeMask) &#123;</span><br><span class="line">            case YYEncodingTypeObject: &#123;</span><br><span class="line">                id v = ((id (*)(id, SEL))(void *) objc_msgSend)((id)model, propertyMeta-&gt;_getter);</span><br><span class="line">                value = ModelToJSONObjectRecursive(v);</span><br><span class="line">                if (value == (id)kCFNull) value = nil;</span><br><span class="line">            &#125; break;</span><br><span class="line">            case YYEncodingTypeClass: &#123;</span><br><span class="line">                Class v = ((Class (*)(id, SEL))(void *) objc_msgSend)((id)model, propertyMeta-&gt;_getter);</span><br><span class="line">                value = v ? NSStringFromClass(v) : nil;</span><br><span class="line">            &#125; break;</span><br><span class="line">            case YYEncodingTypeSEL: &#123;</span><br><span class="line">                SEL v = ((SEL (*)(id, SEL))(void *) objc_msgSend)((id)model, propertyMeta-&gt;_getter);</span><br><span class="line">                value = v ? NSStringFromSelector(v) : nil;</span><br><span class="line">            &#125; break;</span><br><span class="line">            default: break;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    if (!value) return;</span><br><span class="line"></span><br><span class="line">    if (propertyMeta-&gt;_mappedToKeyPath) &#123;</span><br><span class="line">        NSMutableDictionary *superDic = dic;</span><br><span class="line">        NSMutableDictionary *subDic = nil;</span><br><span class="line">        for (NSUInteger i = 0, max = propertyMeta-&gt;_mappedToKeyPath.count; i &lt; max; i++) &#123;</span><br><span class="line">            NSString *key = propertyMeta-&gt;_mappedToKeyPath[i];</span><br><span class="line">            if (i + 1 == max) &#123; // end</span><br><span class="line">                if (!superDic[key]) superDic[key] = value;</span><br><span class="line">                break;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            subDic = superDic[key];</span><br><span class="line">            if (subDic) &#123;</span><br><span class="line">                if ([subDic isKindOfClass:[NSDictionary class]]) &#123;</span><br><span class="line">                    subDic = subDic.mutableCopy;</span><br><span class="line">                    superDic[key] = subDic;</span><br><span class="line">                &#125; else &#123;</span><br><span class="line">                    break;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; else &#123;</span><br><span class="line">                subDic = [NSMutableDictionary new];</span><br><span class="line">                superDic[key] = subDic;</span><br><span class="line">            &#125;</span><br><span class="line">            superDic = subDic;</span><br><span class="line">            subDic = nil;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        if (!dic[propertyMeta-&gt;_mappedToKey]) &#123;</span><br><span class="line">            dic[propertyMeta-&gt;_mappedToKey] = value;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;];</span><br></pre></td></tr></table></figure>
<p>当模型值为自定义类型时，需要遍历和递归其映射表<code>_mapper</code>（{属性名: 属性元}），通过消息发送 <code>objc_msgSend</code> 的方式，调用属性的 <code>meta-&gt;_getter</code> 方法进行取值，直至逐一转化成有效的JSON对象。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">if (modelMeta-&gt;_hasCustomTransformToDictionary) &#123;</span><br><span class="line">    // 校验数据</span><br><span class="line">    BOOL suc = [((id&lt;YYModel&gt;)model) modelCustomTransformToDictionary:dic];</span><br><span class="line">    if (!suc) return nil;</span><br><span class="line">&#125;</span><br><span class="line">return result;</span><br></pre></td></tr></table></figure>
<p>最后，判断使用者是否有额外的转换处理，并并校验数据的有效性。</p>
<blockquote>
<p>注意：<code>result</code> 和 <code>dic</code> 指向的是同一个实例，所以如果 <code>dic</code> 在外部函数中被修改了，等同于修改了 <code>result</code>。</p>
</blockquote>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><ul>
<li>YYModel的使用无侵入性，采用Category的方式实现功能，比较灵活。</li>
<li>容错方面，YYModel对数据类型做了详细的分类和判断，就算转换失败，也会自动留空（nil）。</li>
<li>性能方面，使用 <code>CoreFoundation</code>、内联函数、runtime、缓存机制等方式，减少不必要的开销。</li>
</ul>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/YYModel/" rel="tag">YYModel</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB/" rel="tag">源码阅读</a></li></ul>

    </footer>
  </div>

    
 
    
</article>

    
  </article>
  

  
  <nav class="page-nav">
    
    <span class="page-number current">1</span><a class="page-number" href="/page/2/">2</a><a class="page-number" href="/page/3/">3</a><a class="extend next" rel="next" href="/page/2/">下一页</a>
  </nav>
  
</section>
</div>

      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2018-2022
        <i class="ri-heart-fill heart_icon"></i> GG266
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></span>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
      <li>
          <img src="/images/beian.png"></img>
          <a href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=33010902002204" target="_black" rel="nofollow">浙公网安备 33010902002204号</a>
      </li>
        
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s4.cnzz.com/z_stat.php?id=1280804963&amp;web_id=1280804963'></script>
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="DJ Hong&#39;s BLOG"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://gitee.com/hongdongjie/gg266picgo/raw/master/pic4blog/alipay.JPG">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://gitee.com/hongdongjie/gg266picgo/raw/master/pic4blog/wechat.JPG">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-3.6.0.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->
 
<script src="/js/busuanzi-2.3.pure.min.js"></script>
 
<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->

<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    <div id="music">
    
    
    
    <iframe frameborder="no" border="1" marginwidth="0" marginheight="0" width="200" height="52"
        src="//music.163.com/outchain/player?type=2&id=1908797593&auto=1&height=32"></iframe>
</div>

<style>
    #music {
        position: fixed;
        right: 15px;
        bottom: 0;
        z-index: 998;
    }
</style>
    
    

  </div>
</body>

</html>